Search code examples
htmlcsshoverborder

Remove style from prev/next element when hovering on element


Example:

http://jsfiddle.net/JUmHG/3

When mouse is over on a LI, the top/bottom border of the LI becomes transparent (replaced by background-color).

But also the bottom-border of the previous LI and the top-border of the next LI must be transparent as well. Can this be done with CSS ?


Solution

  • You cannot select the previous sibling, but you can try some tricks to get the desired effect.

    Like this:

    demo

    Use just border-top & an inset box-shadow on every list item but the fist one in order to mimic the etched top border.

    li{
        border-top: 1px solid #999;
        box-shadow: inset 0 1px 0 #fff;
        padding: 10px;
    }    
    li:first-child{
        border-top: 0;
        box-shadow: none;
    } 
    

    Then remove it on hover for the current item and the item that comes right after it.

    li:hover, li:hover + li {
        border-color: transparent;
        box-shadow: none;
    }
    

    This works in all browsers that support box-shadow (that is, everything except IE8 and older and less capable mobile browsers).

    The same effect could be achieved in IE8 by using an absolutely positioned pseudo-element that is given top: 0; left: 0; height: 1px; width: 100%; background: #fff; (and even in IE7, by adding a child to the list item instead of the pseudo-element). However, I think it's overkill, especially since the original method degrades gracefully.