Answer:
The best way to do this according to your functionality is to use a child element that is positioned absolutely to the <a>
that will serve as the border:
HTML:
<li class="nav1"><a href="http://www.google.com/">home<b/></a></li>
Notice the new <b/>
in there.
CSS:
li.nav1 a, li.nav2 a
{
position: relative;
}
li.nav1 a b, li.nav2 a b
{
position: absolute;
top: 100%;
left: -20px;
display: none;
width: 100%;
height: 3px;
background: red;
padding: 0px 20px;
}
li.nav1 a:hover b, li.nav2 a:hover b{
display: block;
}
By positioning the <a>
elements relatively, I can position a child element, which I called <b>
below it (using top: 100%
). Then by using padding on that element, I can make it wider than the parent and slide it to the left using left: -20px
. (You can change the additional width, but be sure that the same number is set in padding:
and left:
).
Finally, I set its display to be none
normally, and then when the parent <a>
receives a hover event, I set its display to block
using this selector:
li.nav1 a:hover b, li.nav2 a:hover b
JSFiddle
Other ideas:
You could do this with side padding on your <a>
:
li a
{
padding: 0px 20px;
}
JSFiddle
If you want to only extend the <a>
width onHover, you could do this with li a:hover
:
li a:hover
{
padding: 0px 20px;
}
But this will make the links get wider and may affect the position of the links.
JSFiddle
If you want to maintain the <a>
width, you could do this with the entire <li>
and set the margin bottom to be the negative of the border width:
li.nav1:hover, li.nav2:hover {
border-bottom:3px solid red;
margin-bottom: -3px;
}
JSFiddle
Note:
For one thing, in your original fiddle, your top bar's selector was
li.nav1 a:hover {
While your bottom bar's selector was
li.nav2:hover {
So you were adding the padding to the <li>
s, rather than the <a>
s in the second nav.