css – ::伪元素堆栈顺序问题

当静态定位时,:: before伪元素堆栈(z-index)之前的孩子的内容,但是在孩子的背景之后.任何人都可以解释为甚么甚至发生这种情况,或者这是所有主流浏览器都有的问题?
<style>
div { background-color:yellow; width:400px; }
div::before { background-color:red; content:"div::before"; }
div::after { background-color:green; content:"div::after"; }
div p { background-color:blue; color:white; margin:-15px 0; padding:0; }
</style>
<div>
<p>Lorem ipsum dolor sit amet,consectetur adipiscing elit. Aliquam sed tellus sed tellus soDales hendrerit tristique et elit.</p>
</div>

http://jsfiddle.net/funkyscript/ALrgf/

解决方法

包含两个伪元素和p元素的div的内容参与相同的堆栈上下文(相对于div).这是因为,正如你所说,这三个都是静态的;换句话说,根本没有定位. (是的,这些元素在流动的过程中沿着z轴进行堆叠;你根本不能使用z-index操作它们的堆栈级别,因为它们没有定位.)

绘制各部分的顺序的Here’s a summary1,与您的问题相关的大胆重点:

Each Box belongs to one stacking context. Each positioned Box in a given stacking context has an integer stack level,which is its position on the z-axis relative other stack levels within the same stacking context. Boxes with greater stack levels are always formatted in front of Boxes with lower stack levels. Boxes may have negative stack levels. Boxes with the same stack level in a stacking context are stacked back-to-front according to document tree order.

Within each stacking context,the following layers are painted in back-to-front order:

  1. the background and borders of the element forming the stacking context.
  2. the child stacking contexts with negative stack levels (most negative first).
  3. the in-flow,non-inline-level,non-positioned descendants.
  4. the non-positioned floats.
  5. the in-flow,inline-level,non-positioned descendants,including inline tables and inline blocks.
  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  7. the child stacking contexts with positive stack levels (least positive first).

由于div :: before被插入到div的内容之前,并且div :: after被插入到它之后,当它们以静态位置显示为内联时,它们自然地遵循这个规则,即使是夹着块元素两个框框和内嵌框都考虑在内).

请注意,由于明显的原因,背景通常是首先绘制的,其内容与之相反:

> p元素作为块级元素具有首先绘制的背景(#3).
>然后在p背景(#5)上绘制其背景的内联级伪元素.在格式模型中,它们是p元素的兄弟,所以它们都参与div的堆叠上下文而不是p的堆叠上下文.
> div :: before伪元素(它的内容和背景)出现在p文本的后面,因为它在视觉树中的p之前.
> div :: after伪元素(其内容和背景)出现在p文本的前面,因为它在视觉树中的p之后.

如我的评论if you make the pseudo-elements display as blocks所示,div :: before的背景将隐藏在p元素之后,而不是文本;相反,div :: before的文本将位于p元素的背景和文本之间.还要注意,div :: after的背景画在p的前面,而内容是最前面的.再次,这与在上述规则之前或之后的背景相关的背景有关.

1更详细的描述可以在Appendix E中找到.

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效