0

i have this Html Code:

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
</ul>

ex : When <li>4</li> Mouse is Hover > <li>3</li> & <li>5</li> Set Style...

ex : When <li>2</li> Mouse is Hover . <li>1</li> & <li>3</li> Set Style...

can do this without using Jquery? Thnaks

  • 2
    Without jQuery, yes - but you'd still need Javascript for the previous-sibling part. See: http://stackoverflow.com/questions/1817792/css-previous-sibling-selector – Paul Roub Aug 13 '13 at 13:55

3 Answers3

4

You can use the + selector to select the next element:

li:hover + li {
    background-color: red;
}

There is not a selector for the previous element.

Edit: here is a way to do it similar to gvee's answer.

Community
  • 1
  • 1
Michael Lawton
  • 1,460
  • 1
  • 14
  • 25
2

I think I might have cracked this in pure CSS... it does contain a bit of a hack to reverse the natural z-index which I don't like, but it sorts things out.

The theory is this: you set a fixed height for the li and give it a border-top-width of the same value. You can then "stack" the list items on top of one and other so that the top border can "pretend" to be the background for the item above.

Enough gassing let's show the code...

JSFiddle: http://jsfiddle.net/gvee/Awjmp/

HTML

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>

CSS

* {
    margin: 0;
    border: 0;
    padding:0;
}
ul {
    width: 200px;
    border: 1px solid black;
    list-style-type: none;
    background-color: #eee;
    margin: 10px;
    overflow: hidden;
    /* stop the first item's border bursting the container */
}
li {
    height: 20px;
    border-top-width: 20px;
    /* li.height */
    border-top-style: solid;
    border-top-color: #eee;
    /* ul.background-color */
    position: relative;
    margin-top: -20px;
    /* -li.height */
}
li:hover {
    background-color: red;
    /* "current" colour */
    border-top-color: yellow;
    /* "previous" colour */
}
li:hover + li {
    background-color: lime;
    /* "next" colour */
}
/* HACK... reverse the natural z-index */
 li:nth-child(9) {
    z-index: 1
}
li:nth-child(8) {
    z-index: 2
}
li:nth-child(7) {
    z-index: 3
}
li:nth-child(6) {
    z-index: 4
}
li:nth-child(5) {
    z-index: 5
}
li:nth-child(4) {
    z-index: 6
}
li:nth-child(3) {
    z-index: 7
}
li:nth-child(2) {
    z-index: 8
}
li:nth-child(1) {
    z-index: 9
}
gvee
  • 16,732
  • 35
  • 50
0

JSFiddle: http://jsfiddle.net/gvee/q6QS5/

HTML

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
</ul>

CSS

li:hover
{
    background-color: red;
}

li:hover + li
{
    background-color: lime;
}

.previous
{
    background-color: blue;
}

JQuery

This is needed to get the "previous" item highlighted

$('li').hover(function() {
    $(this).prev().toggleClass('previous');
});
gvee
  • 16,732
  • 35
  • 50