CSS浮动重叠问题

31

我正在尝试为我的网页设置一个简单的水平标签结构,但是我在使用浮动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个回答

73

z-index属性不会应用于静态定位的元素。为了使用z-index,CSS还必须包括除static(即relative,absolute,fixed)以外的任何位置值。

.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; }

我认为这将给你想要的东西。我添加了position: relative; 并且将 .left 的 z-index 更改为3(从2),同时将 .right 的 z-index 更改为2(从3)。


8

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


2
或者 position: relative; - Kevin Wheeler

2

使用position属性来控制元素的位置。在.left中添加position:relative


0
负的 `margin-left`?
.right { float: left; width: 396px; background-color: #09c; border: 2px solid green; z-index: 3; margin-left: -5px;}

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