我试图为我正在工作的页面设置一个简单的水平制表结构,我遇到一些麻烦与浮动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的橙色边框不重叠右边的绿色边框?
解决方法
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; }
会给你你想要我想的。我添加了position:relative;并将.left的z-index更改为3(从2),并将.right的z-index更改为2(从3)。