Reputation: 107
I have the following code and when you run the code, the box/block automatically moves from its place and finally reaches the starting point after completing a square cycle (Left -> Right -> Bottom -> Left -> Top). I want the box to move from its place only when it is hovered over. The original code is:
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
position: relative;
animation-name: example;
animation-duration: 4s;
}
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
I tried to insert the "hover" attribute using CSS but it doesn't work (the code is completely ignored). How can I modify the code such that the block only moves from its place when it's hovered over and when the cursor is removed from it, it goes back to its original place?
Upvotes: 3
Views: 324
Reputation: 567
You need a container to do that, try this:
<html>
<head>
<style>
.block {
width: 100px;
height: 100px;
background-color: red;
position: relative;
}
.container:hover .block {animation-name: example; animation-duration: 4s;}
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div class='container'>
<div class='block'></div>
</div>
</body>
</html>
Or, you can try this too. But make sure your mouse always hovering the block.
<html>
<head>
<style>
.block {
width: 100px;
height: 100px;
background-color: red;
position: relative;
}
.block:hover {animation-name: example; animation-duration: 4s;}
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div class='block'></div>
</body>
</html>
Upvotes: 3