Akshay
Akshay

Reputation: 14348

z-index not working properly with nth-child

I have three sortable lists here, but i don't want their property to change when their position is changed.For example i can prevent their color from changing but can't do the same thing with z-index i am using nth-child to do this here is my code http://codepen.io/anon/pen/pvEdMw

HTML

<ul>
<li>aaa</li>
<li>aaaasdsd</li>
<li>fgf</li>
</ul>

CSS

li{
position:relative;
background-color:orange;
}

li:nth-child(1){
box-shadow:2px 2px 2px black;
z-index:3;
color:red;
}

li:nth-child(2){
box-shadow:2px 2px 2px black;
z-index:2;
color:blue;
} 

li:nth-child(3){
box-shadow:2px 2px 2px black;
z-index:1;
color:green;
}

JQuery

$('ul').sortable();

Upvotes: 2

Views: 1263

Answers (1)

t.niese
t.niese

Reputation: 40852

sortable function of jquery-ui also makes use of z-index. It directly modifies the style of the element and is setting the z-index which overwrites your style.

One way how you can fix that problem is by using !important on the z-index.

li:nth-child(1){
  box-shadow:2px 2px 2px black;
  z-index:3 !important;
  color:red;
}

But I really don't like the usage of !important, as it might break other rules you have and will make your css code harder to maintain.

The other way would be to hook into the stop callback and cleanup the z-index set by the sortable plugin.

$('ul').sortable({
  stop: function( event, ui ) {
    $(this).find('li').css('z-index','');
  }
});

Upvotes: 5

Related Questions