我正在尝试为我正在处理的页面设置一个简单的水平制表符结构,而且我遇到浮动div与z-index相结合的问题。
在浏览器中查看以下代码:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#main { width: 500px; z-index: 1;}
.left { float: left; width: 96px; background-color: red; border: 2px solid orange; z-index: 2; margin-right: -2px }
.right { float: left; width: 396px; background-color: #09c; border: 2px solid green; z-index: 3; }
.clear { clear: both; }
</style>
</head>
<body>
<div id="main">
<div class="left">
LEFT
</div>
<div class="right">
RIGHT
<br />
RIGHT
</div>
<div class="clear"></div>
</div>
</body>
</html>
为什么左侧div的橙色边框与右侧div的绿色边框重叠?
答案 0 :(得分:64)
z-index属性不适用于静态定位的元素。为了使用z-index,CSS还必须包含静态以外的任何位置值(即相对值,绝对值,固定值)。
.left { float: left; width: 96px; background-color: red; border: 2px solid orange; z-index: 3; margin-right: -2px; position: relative; }
.right { float: left; width: 396px; background-color: #09c; border: 2px solid green; z-index: 2; position: relative; }
会给你我想要的东西。我添加了位置:相对;并将.left的z-index更改为3(从2开始),并将.right的z-index更改为2(从3开始)。
答案 1 :(得分:8)
z-index
对未定位的元素(例如position:absolute;
)
答案 2 :(得分:2)
对元素upper使用position
属性。将position:relative
添加到.left
。
答案 3 :(得分:0)
否定margin-left
?
.right { float: left; width: 396px; background-color: #09c; border: 2px solid green; z-index: 3; margin-left: -5px;}