30

我正在尝试为我正在处理的页面设置一个简单的水平选项卡结构,并且在浮动 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 的绿色边框重叠?

4

4 回答 4

69

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)。

于 2009-02-23T23:01:43.720 回答
8

z-index对未定位的元素没有影响(例如position:absolute;

于 2009-02-23T23:02:24.123 回答
2

使用position元素上部的属性。添加position:relative.left.

于 2015-03-26T03:21:59.390 回答
0

负数margin-left

.right { float: left; width: 396px; background-color: #09c; border: 2px solid green; z-index: 3; margin-left: -5px;}
于 2009-02-23T23:04:46.380 回答