Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line below link on hover

Tags:

html

css

How can I add a short line below link ? The line should be visible only on hover. I tried with border-bottom, but that way the line is 100% of the link width and I want the line to be shorter than the link .

Here is a example image of the effect that I try to make.

enter image description here

like image 241
user2013488 Avatar asked May 13 '14 12:05

user2013488


3 Answers

You can try using ::after pseudo element:

a {
  position: relative;
  text-decoration: none;
}

a:hover::after {
  content: "";
  position: absolute;
  left: 25%;
  right: 25%;
  bottom: 0;
  border: 1px solid black;
}
<a href='#'>Demo Link</a>
like image 138
T J Avatar answered Sep 20 '22 09:09

T J


This is something I just thought of, check it out see what you think. So we use :after and create a line under the text. This only works if the parent has a width (for centering).

HTML:

<div>Test</div>

CSS:

div {
    width: 30px;
}
div:hover:after {
    content: "";
    display: block;
    width: 5px;
    border-bottom: 1px solid;
    margin: 0 auto;
}

DEMO


Updated CSS:

div {
    display: inline-block;
}

Not sure why I didnt think of this but you can just use inline-block to get it to center without the parent having a width.

DEMO HERE


Here is a link using the same method, just incase you got confused.

DEMO HERE


So I have now be told I should even point out the most obvious thing so here is an update just for the people that don't know width can be a percentage.

width: 70%;

Changed the width from 5px to 70% so it will expand with the width of the text.

DEMO HERE

like image 33
Ruddy Avatar answered Sep 20 '22 09:09

Ruddy


Edit: Ruddy's solution has the same result and is more elegant so based on that, I used it recently with addition of transition, making it a bit more eye catching and I thought it would be useful to share here:

 a {
   display: inline-block;
   text-decoration:none
 }
 a:after {
   content: "";
   display: block;
   width: 0;
   border-bottom: 1px solid;
   margin: 0 auto;
   transition:all 0.3s linear 0s;
 }

 a:hover:after {
   width: 90%;
 }

jsfiddle link

(Original answer below)

Check this i just came up with, playing in the fiddle:

 <a class="bordered" href="#">I am a link, hover to see</a>


 a.bordered {  
 text-decoration:none;
 position: relative;
 z-index : 1;
 display:inline-block;
 }

a.bordered:hover:before {
content : "";
position: absolute;
left    : 50%;
bottom  : 0;
height  : 1px;
width   : 80%;
border-bottom:1px solid grey;
margin-left:-40%;
}

Depending on the percentages, you may play with a.bordered:hover:before margin and left position.

like image 45
alou Avatar answered Sep 18 '22 09:09

alou