Why is my element with position:absolute always showing up underneath position:relative items?

喜你入骨 提交于 2019-12-07 16:08:52

问题


It's all in the question but here's a simple example

<!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>

回答1:


instead of "z-layer" use "z-index"

also the absolute span is in a relative div with no z-index

Here is the correct 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>



回答2:


It happens because when you position an element "absolutely" it is removed from the flow of the document in the Document Object Model and so elements that remain in the flow of the document appear "above" the removed element. For cross-browser compatibility place your z-index adjustments on the parent element of the absolutely positioned element.



来源:https://stackoverflow.com/questions/578554/why-is-my-element-with-positionabsolute-always-showing-up-underneath-positionr

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