具有静态位置的元素总是落后于其他元素吗?

时间:2014-09-25 05:37:53

标签: html css

<style type="text/css">
    p.example {
        position: relative;
        top: 25px;
        background-color: red;
        }
</style>

<p class="example">First paragraph</p>
<p>Second paragraph</p>

当我在浏览器中加载此代码时,第一段出现在第二段的顶部,这很奇怪,因为我希望第二段在第一段之后呈现。即使我使用z-index,第二段仍然在后面。静态定位元素总是在后面吗?

5 个答案:

答案 0 :(得分:2)

Z-index应该有用......

p.example {
    position: relative;
    top: 25px;
    background-color: red;
    z-index: -1;
}

请参阅下面的jsfiddle。

http://jsfiddle.net/qddoyvbo/

答案 1 :(得分:1)

<style type="text/css">
div#ex{
    position: relative;
    top: 25px;
}
p.example {
    background-color: red;
}
</style>

HTML:

<div id="ex">
   <p class="example">First paragraph</p>
   <p>Second paragraph</p>
</div>

http://jsfiddle.net/yy4Ldwc5/

答案 2 :(得分:1)

是。定位元素(及其子元素)始终显示在任何非定位元素的前面。 (要说一个元素是&#34;定位&#34;意味着它有一个非静态的位置值,例如相对,绝对等)。

z-index对未定位的元素没有影响,这就是为什么它对你来说似乎无效。这是HTML的标准行为(它遵循W3C specs)。

为了更好地理解这种行为,我建议你阅读这篇更详细解释事情的文章:http://philipwalton.com/articles/what-no-one-told-you-about-z-index/

答案 3 :(得分:0)

如果您希望获得第二个<p>,则必须使用position:relativez-index,因为您已经为position:relative申请了<p>,它来了达

答案 4 :(得分:0)

试试这个

p.example {
  position: relative;
  top: 25px;
  background-color: red;
  z-index: -1;
}
<p class="example">First paragraph</p>
<p>Second paragraph</p>