0

I have the below hover effect which works well. However, I am trying to add a fixed width of the blue line. For example a max-width of 100px. When I try to amend the code below the animation breaks and doesn't grow from the center.

Any ideas on how to fix the code below so it animates from the center to a fixed width?

body {
  width:100%;
}

div {
  display:block;
  position:absolute;
  top:45%;
  left:50%;
  border-bottom:4px solid blue;
  width:0%;
  text-align:center;
  animation: line 2s linear forwards;
}

@keyframes line {
  from {
    left:50%;
    width:0%;
  }
  to {
    left:5%;
    width:90%;
  }
}
<div>Heading</div>
londonfed
  • 1,170
  • 2
  • 12
  • 27

2 Answers2

1

I would use the :after pseudo-element instead of adding the border to the actual element. I also reduced your animation time because it seemed a little long:

body {
  width:100%;
}

div {
  display:inline-block;
  position:absolute;
  top:45%;
  left:50%;
  text-align:center;
}
  div:hover:after {
    content:"";
    display:block;
    width:0;
    margin:0 auto;
    height:4px;
    background:blue;
    animation:line .5s linear forwards;
  }

@keyframes line {
  from {
    width:0%;
  }
  to {
    width:100%;
  }
}
<div>Heading</div>

You can also do this without keyframes like this:

body {
  width:100%;
}

div {
  display:inline-block;
  position:absolute;
  top:45%;
  left:50%;
  text-align:center;
}
  div:after {
    content:"";
    display:block;
    height:4px;
    background:blue;
    width:0;
    margin:0 auto;
    transition:.5s all;
  }
  div:hover:after {
    width:100%;
  }
<div>Heading</div>
APAD1
  • 13,509
  • 8
  • 43
  • 72
  • A similar answer could be found here: http://stackoverflow.com/questions/35066584/how-to-animate-border-transition-expand-with-css – Hardik Mar 20 '17 at 17:41
1

Solution 1

Just add an additional span element for which you can limit the width:

body {
  width: 100%;
}

div {
  display: block;
  position: absolute;
  top: 45%;
  left: 50%;
  width: 0%;
  animation: line 2s linear forwards;
}

.heading {
  display: block;
  text-align: center;
  max-width: 200px;
  border-bottom: 4px solid blue;
  margin: 0px auto;
}

@keyframes line {
  from {
    left: 50%;
    width: 0%;
  }
  to {
    left: 5%;
    width: 90%;
  }
}
<div><span class="heading">Heading</span></div>

Solution 2

Don't use absolute positioning to center your div:

div {
  display: block;
  width: 0%;
  animation: line 2s linear forwards;
  text-align: center;
  max-width: 200px;
  border-bottom: 4px solid blue;
  margin: 0px auto;
}

@keyframes line {
  from {
    width: 0%;
  }
  to {
    width: 90%;
  }
}
<div>Heading</div>
Community
  • 1
  • 1
Marvin
  • 9,164
  • 3
  • 26
  • 44