VIVEK RAJ VIVEK RAJ - 6 months ago 53
CSS Question

Expand bottom border on hover

I'm trying to get a transition effect on border that the border expands on hover.



h1 {
color: #666;
}
h1:after {
position: absolute;
left: 10px;
content: '';
height: 40px;
width: 275px;
border-bottom: solid 3px #019fb6;
transition: left 250ms ease-in-out, right 250ms ease-in-out;
opacity: 0;
}
h1:hover:after {
opacity: 1;
}

<h1>CSS IS AWESOME</h1>





I've tried this on Jsfiddle

Answer

In order to expand the bottom border on hover, you can use transform:scaleX'(); (mdn reference) and transition it from 0.0001 to 1 on the hover state.

Bottom border expand on hover

The border and transition are set on a pseudo element to prevent transitioning the text :

h1 {
  color: #666;
  display:inline-block;
}
h1:after {
  display:block;
  content: '';
  border-bottom: solid 3px #019fb6;  
  transform: scaleX(0.0001);  
  transition: transform 250ms ease-in-out;
}
h1:hover:after {
  transform: scaleX(1);
}
<h1>CSS IS AWESOME</h1>

To expand the bottom border from left or right, you can change the transform-origin property to the left or right of the pseudo element:

h1 { color: #666;display:inline-block; }
h1:after {
  display:block;
  content: '';
  border-bottom: solid 3px #019fb6;  
  transform: scaleX(0.0001);  
  transition: transform 250ms ease-in-out;
}
h1:hover:after { transform: scaleX(1); }
h1.fromRight:after{ transform-origin:100% 50%; }
h1.fromLeft:after{  transform-origin:  0% 50%; }
<h1 class="fromCenter">Expand from center</h1><br/>
<h1 class="fromRight">Expand from right</h1><br/>
<h1 class="fromLeft">Expand from left</h1>

Note : You need to insert vendor prefixes to maximize browser support (see canIuse).

Comments