为什么我的使用position:absolute定位的元素总是出现在使用position:relative定位的元素下面?

6

问题已经很清楚了,这里有一个简单的例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1" />
    <title>TEST</title>
</head>
<body style="margin:0;padding:0">

<div style="background-color:#eeeeee;margin:auto;height:500px;width:500px">
    <div style="position:relative">
        <span style="position:absolute;display:block;height:250px;width:250px;background:green;z-layer:2"><br /><br />Should be on top</span>
    </div>
    <span style="position:relative;display:block;width:500px;background:blue;z-layer:1">Actually on top</span>
</div>

</body>
</html>
2个回答

12

使用"z-index"替代"z-layer"

而且绝对定位的位于一个没有z-index的相对定位的

这是正确的HTML:

<div style="background-color:#eeeeee;margin:auto;height:500px;width:500px">
    <div style="position:relative;z-index:2">
        <span style="position:absolute;display:block;height:250px;width:250px;background:green"><br /><br />Should be on top</span>
    </div>
    <span style="position:relative;display:block;width:500px;background:blue;z-index:1">Actually on top</span>
</div>

4

这是因为当您将元素“绝对”定位时,它会从文档对象模型中的文档流中移除,因此仍在文档流中的元素会显示在被移除的元素的“上方”。为了实现跨浏览器兼容性,请将z-index调整放在绝对定位元素的父元素上。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接