Eunice Chia Eunice Chia - 4 months ago 7
CSS Question

Why isn't my animation element centered?

I'm stuck on this for so long, why the car isn't swerve around the middle line with my animation? it seems like a bit off to the right?



.car {
width: 40px;
height: 60px;
background: #f00;
left: 50%;
transform: translate(-50%, 0);
animation: swerve 2s linear infinite;
top: 10%;
position: absolute;
}
@keyframes swerve {
0% {
transform: translate(-50%, 0);
}
50% {
transform: translate(50%, 0);
}
}
.road {
width: 200px;
background: black;
height: 500px;
display: block;
position: relative;
}
.road-middle {
border: 1px dotted #fff;
transform: rotate(90deg);
display: block;
position: relative;
top: 200px;
}

<div class='road'>
<span class="road-middle"></span>
<div class='car'></div>
</div>





Also how to control the length of the middle's border?

Answer

Adding left: 50% aligns the leftmost edge of your element with the center. To align vertical center of your element with container's center you need to add negative margin equal to half that element's width, which pushes it back to left a little. E.g. here I have added margin-left: -20px; to your car and now it is in center:

.car {
  width: 40px;
  height: 60px;
  background: #f00;
  left: 50%;
  transform: translate(-50%, 0);
  animation: swerve 2s linear infinite;
  top: 10%;
  margin-left: -20px;
  position: absolute;
}
@keyframes swerve {
  0% {
    transform: translate(-50%, 0);
  }
  50% {
    transform: translate(50%, 0);
  }
}
.road {
  width: 200px;
  background: black;
  height: 500px;
  display: block;
  position: relative;
}
.road-middle {
  border: 1px dotted #fff;
  transform: rotate(90deg);
  display: block;
  position: relative;
  top: 200px;
}
<div class='road'>
  <span class="road-middle"></span>
  <div class='car'></div>
</div>