I'm trying to create animation where at the start brand logo is at the middle of the screen and at the end it moves to it's position in navbar. I decided to transform: translate
with viewport units. But it doesn't stay in center. On wider screen it sticks to right side and on smaller screen it's a little bit off center. Also position: absolute
isn't an option since I can't bring logo back to navbar.
Is it possible to center my logo in the middle with only using transform: translate
?
nav {
max-width: 400px;
display: flex;
justify-content: space-between;
margin: auto;
background: #aaa;
padding: 5px 10px;
}
.brand {
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
}
.test {
position: absolute;
top: 50vh;
left: 50vw;
transform: translate(-50%, -50%);
}
<nav>
<div >Brand</div>
<div >
<a href="#">Home</a>
<a href="#">Profile</a>
</div>
</nav>
<div >TEST</div>
CodePudding user response:
The initial horizontal translate
value can work properly only when the viewport width is less than 400px
In fact, since your .brand
element is in static position you can't use the vw
unit for the X-axis when the viewport is larger than 400px because your starting point is not (0, 0) of the viewport, but it's (0, 0) of the nav
element: in this case the horizontal offset is calc(200px - 50%)
— since the parent max-width
is 400px
nav {
max-width: 400px;
display: flex;
justify-content: space-between;
margin: auto;
background: #aaa;
padding: 5px 10px;
}
.brand {
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
animation: backtohome 2s linear 1s forwards;
}
@media (min-width: 400px) {
.brand {
transform: translate(calc(200px - 50%), calc(50vh - 50%));
}
}
@keyframes backtohome {
100% { transform: translate(0, 0); }
}
.test {
position: absolute;
top: 50vh;
left: 50vw;
transform: translate(-50%, -50%);
}
<nav>
<div >Brand</div>
<div >
<a href="#">Home</a>
<a href="#">Profile</a>
</div>
</nav>
<div >TEST</div>