Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Absolutely positioned pseudo element loses z-index?

Tags:

css

Why would an absolutely positioned pseudo element be losing its z-index when using transition?

The fiddle: http://jsfiddle.net/RyanWalters/jNgLL/

What's happening? When you click on the li, it slides to the left without changing any z-index values. However, the :after content is popping up on top of the li.

What should happen? I was hoping it would stay hidden behind the li.

The CSS (simplified a little bit, see fiddle for full example):

li {
    position: relative;
    transition: transform 0.2s;
}

li.active {
    transform: translateX(-100px);
}

li:after {
    position: absolute;
    top: 0;
    right: 0;
    z-index: -1;
    content: "Yada yada";
}

Why is the :after content not staying behind the li?

like image 600
Ryan Avatar asked Nov 14 '13 21:11

Ryan


2 Answers

I found this on w3.org, which I think explains it: http://www.w3.org/TR/css3-transforms/#effects

Any value other than ‘none’ for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.

As I understand it, your li:after pseudo-element is inside the stacking context of the li.active element, and therefore cannot appear behind it.

like image 102
BernzSed Avatar answered Sep 29 '22 03:09

BernzSed


@BernzSed's answer is correct. Here's a solution, though:

Wrap the content inside the <li> using a <div> (or any other element) with position: relative, then the z-index: -1 on the psuedo element will force it to be behind the child element.

Here's the essential code:

HTML:

<ul>
  <li><div>This is the first item</div></li>
</ul>

CSS:

li,
li div {
  position: relative;
}

li:after {
  position: absolute;
  z-index: -1;
}

Example: http://jsfiddle.net/shshaw/jNgLL/3/

Also interesting to note: If you use a :before psuedo element, you don't need the z-index: -1 because it's already falling under the position: relative child element in the stacking order.

like image 35
shshaw Avatar answered Sep 29 '22 01:09

shshaw