Z-index with before pseudo-element

与世无争的帅哥 提交于 2019-11-26 07:41:28

问题


I\'ve created a \'header\' element with a before-pseudo element. the pseudeo element must be behind the parent element. Everything works great till the moment I give my \'header\' a z-index.

What I want: The yellow \'header\' on the foreground, the red pseudo-element in the background and a simple z-index of 30 on the yellow \'header\' element.

header { 
    background: yellow;
    position:relative;
    height: 100px;
    width: 100px;
    z-index:30; /*This is the problem*/
}

header::before { 
    content:\"Hide you behind!\";
    background: red;
    position:absolute;
    height: 100px;
    width: 100px;
    top:25px;
    left:25px;
    z-index:-1;
}

You can test my problem on this link (http://jsfiddle.net/tZKDy/) and you see the problem when you set/remove the z-index on de \'header\' element.


回答1:


The ::before pseudo-element is placed inside the header element.

CSS Spec:

The :before and :after pseudo-elements interact with other boxes as if they were real elements inserted just inside their associated element.

Setting the z-index for the header element creates a new Stacking Context, so the new pseudo element you created can not float behind the header element, because it would have to go outside that Stacking Context.

I suggest that you simply precede the header element by another element, so it stacks correctly by default. Example.



来源:https://stackoverflow.com/questions/7822078/z-index-with-before-pseudo-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!