Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate border transition expand with CSS?

Tags:

html

css

border

I'm trying to create a CSS transition where the border-bottom of a href element expands on :hover to the width of the link.

What I could find is a CSS solution where the background width is animated: http://jsfiddle.net/mfn5nefb/82/

But that's not what I want, because after click on a navigation tab I want to leave the border as is. So I'd have to directly animate the border, instead of the background.

<!-- assume the border-bottom is only applied to an active=clicked navigation tab -->
<h1 style="border-bottom: 3px solid green;">CSS IS AWESOME</h1>

h1 {
    color: #666;
    position: relative;
    display: inline-block;
}

h1:after {
    position: absolute;
    left: 50%;
    content: '';
    height: 40px;
    height: 5px;
    background: #f00;
    transition: all 0.5s linear;
    width: 0;
    bottom: 0;  
}

h1:hover:after {
    width: 270px;
    margin-left: -135px;
}

Here you see the "active" link gets a green border. And on hover I'd like to animate the other tabs, but the border itself. Currently the background is animated, which appears above the border and thus looks misaligned.

like image 625
membersound Avatar asked Dec 08 '22 23:12

membersound


1 Answers

You can still achieve this by using a pseudo-element (with background) and expand it on hover. All that is required is to set the value for the bottom property as the inverse of expected border-width and also set the height of the pseudo-element to be the same as the border-width.

h1 {
  color: #666;
  position: relative;
  display: inline-block;
}
h1:after {
  position: absolute;
  left: 50%;
  content: '';
  height: 3px;
  background: #f00;
  transition: all 0.5s linear;
  width: 0;
  bottom: -3px;
}
h1:hover:after {
  width: 100%;
  left: 0px;
}
<!-- assume the border-bottom is only applied to an active=clicked navigation tab -->
<h1 style="border-bottom: 3px solid green;">Tab1</h1>
<h1>Tab2</h1>

Another way to achieve the same effect using the border property itself would be to use transform: scale like in the below snippet. Here the scaleX(0) makes the original width of the element as 0 and on hover it is transitioned to full width using scaleX(1). Since, default transform-origin is at 50% in X-axis, the border looks as though it is expanding from the center.

h1 {
  color: #666;
  position: relative;
  display: inline-block;
}
h1:after {
  position: absolute;
  left: 0%;
  top: 0%;
  content: '';
  height: 100%;
  transition: all 0.5s linear;
  width: 100%;
  border-bottom: 3px solid red;
  transform: scaleX(0);
}
h1:hover:after {
  transform: scale(1);
}
<!-- assume the border-bottom is only applied to an active=clicked navigation tab -->
<h1 style="border-bottom: 3px solid green;">Tab1</h1>
<h1>Tab2</h1>
like image 57
Harry Avatar answered Dec 27 '22 07:12

Harry