Yahreen
Yahreen

Reputation: 1669

Adding a CSS Border on Hover and Removing It in jQuery

I'm attempting to add a class to a group of floated list items on hover using jQuery.

I add the class and then remove the added space from the newly-inserted border using margin:-4px so that the list items do not shift around.

That's my intention at least. it's not working. Here is a fiddle:

http://jsfiddle.net/NgXSc/1/

Note how the sibling list items shift on hover. The intended result is the very last list item where upon hovering, nothing moves.

Upvotes: 2

Views: 969

Answers (4)

Tim B James
Tim B James

Reputation: 20364

Dont mess about with negative margins. Change your .over class to

#cs-client-list li a.over{ border: 4px solid #000; width: 103px; }

This is the quickest way to get your desired effect without applying a transparent border to the non-hover state li a elements.

Upvotes: 0

Wex
Wex

Reputation: 15695

Your margin problem is being caused because although you initially define the margin to be margin-right: 19px, you overwrite it with margin: -4px !important.

Also, there's no need to use jQuery for this - just use the :hover CSS pseudoclass.

I modified your code to produce your desired results:

HTML:

<nav id="cs-client-list">
    <ul>
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
        <li><a href="#">C</a></li>
        <li><a href="#">D</a></li>
    </ul>
</nav><!--end cs-client-list-->

CSS:

#cs-client-list { padding: 25px; }
#cs-client-list li {
    background: yellow;
    float:left;
    margin: 0 19px 0 0;}
#cs-client-list li a {
    text-indent: -99999px;
    width: 111px;
    height: 80px;
    border: 4px solid transparent; /* use page's background color (ie #fff) if you want the border to display outside the box */
    display: block; }
#cs-client-list li a:hover { border-color: #000; }

Preview: http://jsfiddle.net/Wexcode/NgXSc/26/

Upvotes: 1

Chris C
Chris C

Reputation: 2013

margin: -4px is not a relative change to 19px. It completely replaces it.

Figuring out that padding adds 4px to both the left and right, you want to subract 8 pixels from the margin and use margin-right: 11px for the .over class. This keeps the list items in their original positions.

See the change in code here: http://jsfiddle.net/NgXSc/21/

Upvotes: 1

David Thomas
David Thomas

Reputation: 253328

Set a transparent border (or set the border-color to the background-color of the element) on the non-hovered element equal to the width of the visible border on the hovered-over element. And remove the !important; it's not necessary, just use specificity:

#cs-client-list li a{float:left;display:block;text-indent:-99999px;height:80px;background-color:yellow;width:111px; border: 4px solid transparent;}

#cs-client-list li a.over{border:4px solid #000;cursor:pointer;}

Updated JS Fiddle

This does not need jQuery, not even in IE6...

Upvotes: 0

Related Questions