2
votes

I have the following CSS which I'm using to create a simple hover effect for a handful of links in a navbar:

#k9nav-inner ul li:hover {
    background-color: black;
    border-bottom: 2px solid red;
}

It works, but the border at the bottom is pushing the entire bottom part of the navbar those 2px (in other words, the navbar's height is increasing by 2px during the hover), resulting in a noticeable popping effect when the mouse moves over/off of the links. I see how that would happen with the box model, but is there any way to counteract it so the 2px border appears, but doesn't stretch the navbar by those same 2px?

4

4 Answers

5
votes

Figured it out:

#k9nav-inner ul li:hover a {
    box-shadow: 0 -2px red inset;
}
3
votes

this will stop that that from happening

#k9nav-inner ul li:hover {
    box-shadow: 0 0 0 2px red inset;
}

it's not officially a border , but it looks exactly like one, and won't mess up the box-model sizing

EDIT :

for bottom border only, this will work

#k9nav-inner ul li:hover {
    box-shadow: 0 2px red;
}

example fiddle http://jsfiddle.net/qVD8K/

1
votes

In some cases it can be useful to leverage outline instead of border. Outline does not increase size of a parent container. However, I don't believe an outline can be set on a single side (e.g. outline-bottom).

outline: 2px solid red;

If you add a 2px border to the list elements when they are not hovered using the container's background color for the border then you won't see the 2px shift on hover.

#k9nav-inner ul li {
    border-bottom: 2px solid white;
}
0
votes

You could set transparent border to #k9nav-inner ul li or (which is beter in my opinion) set parent background color.

For example:

HTML:

<div class="sadf sd1">Some text here</div>
<div class="sadf sd2">Some text here</div>
<div class="sadf sd3">Some text here</div>
<div class="sadf sd4">Some text here</div>

CSS:

.sadf {margin:5px; background:#aaa; height:40px;width:150px;}
.sd1:hover {border-bottom:2px solid #000;}
.sd2 {border-bottom:2px solid transparent;}
.sd2:hover {border-bottom:2px solid #f00;}
.sd3 {border-bottom:2px solid #fff;}
.sd3:hover {border-bottom:2px solid #f00;}

Proper working examples is .sd2 and .sd3. As you can see they are not ideal but works fine for me.

See working example on JSFiddle: http://jsfiddle.net/mZg4N/