13

How do I create an underline animation from left to right on hover in CSS3?

Claudio
  • 884
  • 1
  • 15
  • 31
ziltoid
  • 141
  • 1
  • 1
  • 4

1 Answers1

25

This was a really tricky question.

The only solution I can come up with is to transition a border-bottom on :hover or I should actually say that I'm transitioning border-bottom, width and margin-right to make the border-bottom appear and at the same time keep, in this case, the links aligned.

Hard to explain, so I made a quick example which isn't perfect and looks a bit messy, but at least it shows how I mean. :-)

FIDDLE

HTML

<a href="#">Link</a><a href="#">Link</a>

CSS

a {
    text-decoration: none;
    display: inline-block;
    border-bottom: 1px solid blue;    
    margin-right: 39px; 
    width: 0px;
    -webkit-transition: 0.5s ease;
            transition: 0.5s ease;
}

a:hover {
    -webkit-transition: 0.5s ease;
            transition: 0.5s ease;
    border-bottom: 1px solid blue;
    width: 30px;
    margin-right: 9px;
}
Claudio
  • 884
  • 1
  • 15
  • 31
Christofer Vilander
  • 17,232
  • 6
  • 31
  • 26
  • 6
    Setting the width to 0 and thereby have the actual content flow out of the links could have side effects on the rest of the layout. I’d suggest using a generated element (:after) instead, position it absolute at the bottom of the link, and than animate the width of that pseudo element instead. – CBroe Mar 19 '13 at 10:53