I have a relatively positioned box that works as a container for another 4 smaller absolutely positioned squares. I want that when doing :hover
on the container, all the boxes move clockwise, but smoothly. I tried to do it using the properties of position
( top
, right
, bottom
and left
), however. the movement of the boxes is not animated, as shown below:
.container{
height: 300px;
width: 300px;
margin: 20px auto;
background: #ddd;
position: relative;
transition: all 1s;
}
.container__box-1{
height: 50px;
width: 50px;
background: #f00;
position: absolute;
top: 0;
}
.container__box-2{
height: 50px;
width: 50px;
background: #0f0;
position: absolute;
right: 0;
}
.container__box-3{
height: 50px;
width: 50px;
background: #0ff;
position: absolute;
bottom: 0;
}
.container__box-4{
height: 50px;
width: 50px;
background: #00f;
position: absolute;
bottom: 0;
right: 0;
}
.container:hover > .container__box-1{
right: 0;
transition: all 1s;
}
.container:hover > .container__box-2{
bottom: 0;
transition: all 1s;
}
.container:hover > .container__box-3{
top: 0;
transition: all 1s;
}
.container:hover > .container__box-4{
left: 0;
transition: all 1s;
}
<div class="container">
<div class="container__box-1"></div>
<div class="container__box-2"></div>
<div class="container__box-3"></div>
<div class="container__box-4"></div>
</div>
transition
It's not working for me in that case. However, using the property margin
does work for me:
.container{
height: 300px;
width: 300px;
margin: 20px auto;
background: #ddd;
position: relative;
transition: all 1s;
}
.container__box-1{
height: 50px;
width: 50px;
background: #f00;
position: absolute;
top: 0;
}
.container__box-2{
height: 50px;
width: 50px;
background: #0f0;
position: absolute;
right: 0;
}
.container__box-3{
height: 50px;
width: 50px;
background: #0ff;
position: absolute;
bottom: 0;
}
.container__box-4{
height: 50px;
width: 50px;
background: #00f;
position: absolute;
bottom: 0;
right: 0;
}
.container:hover > .container__box-1{
margin-left: calc(300px - 50px);
transition: all 1s;
}
.container:hover > .container__box-2{
margin-top: calc(300px - 50px);
transition: all 1s;
}
.container:hover > .container__box-3{
margin-bottom: calc(300px - 50px);
transition: all 1s;
}
.container:hover > .container__box-4{
margin-right: calc(300px - 50px);
transition: all 1s;
}
<div class="container">
<div class="container__box-1"></div>
<div class="container__box-2"></div>
<div class="container__box-3"></div>
<div class="container__box-4"></div>
</div>
But I want to move the boxes in an animated way without using margins, that is, by positioning. Is there a way to do this without Javascript?
For it to work with
top
,bottom
,left
andright
, to begin with you only need to put atransition: all 0.4s;
in the div's that you want to move, and once positioned (withtop
,bottom
,left
andright
) in the hover we have to change the same property, I leave you as I have done it, Hope this can help you.