Animate horizontal line in css

Hello! I would really want to make a horizontal line animate to each side at the same time.

Meaning starting from 0px in the middle and out to f.ex 40px on both left and right at the same time.

I am using keyframes to animate. Thank you in advance! :slight_smile:

Hello @heleneiskoglund :wave: ! I know I didn’t use @keyframes but I used a pseudo element (::after) and the transform property.

Example:


<style>
* {
	margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.container {
	display: flex;
    justify-content: center;
    align-items: center;
    background-color: #00001A;
    width: 100%;
    height: 100vh;
}

h1 {
    color: #fff;
  	font-family: 'Raleway', sans-serif;
    position: relative;
}

.line h1::after {
    content: '';
    display: block;
    position: absolute;
    top: 115%;
    left: 0;
    bottom: 0;
    background-color: #fff;
    width: 100%;
    height: 3px; 
    transform: scale(0);
    transition: transform 250ms ease-in;
}

.line h1:hover::after {
    transform: scale(1);
}

</style>

<html>
  <body>
	<div class="container line">
	  <h1>Horizontal Line Animation</h1>
	</div>
  </body>
</html>

I hope this helped :smiley:.

Example (untested, I’ll put a codepen example up when I’ve got a sec):

<hr class="animated" />
hr.animated {
  width: 80px;
  animation: expand .5s ease-in-out;
}

@keyframes expand {
  from: {
    transform: scaleX(0);
  }
  to: {
    transform: scaleX(1);
  }
}

Basically, always try to use properties like transform that trigger hardware-acceleration. And scale will do exactly what you want here

Edit: ah, snap! Basically same solution, I’d left my tab open for ages so didn’t see yours before I hit post @waelbouhaya, sorry!

1 Like

Hello @DanCouper! It’s okay :smiley:.