CSS 浮动重叠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/579753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:19:55  来源:igfitidea点击:

CSS Floating with Overlap

cssz-indexcss-float

提问by Michael

I'm trying to set up a simple horizontal tab structure for a page I'm working on, and I'm running into some trouble with floating div's combined with z-index.

我正在尝试为我正在处理的页面设置一个简单的水平选项卡结构,但在将浮动 div 与 z-index 结合时遇到了一些麻烦。

Viewing the following code in a browser:

在浏览器中查看以下代码:

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

Why doesn't the left div's orange border overlap the right div's green border?

为什么左侧 div 的橙色边框不与右侧 div 的绿色边框重叠?

回答by Joshua Shannon

z-index property will not apply to statically positioned elements. In order to use z-index the CSS must also include any position value other than static (ie relative, absolute, fixed).

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

Will give you what you want I think. I added position: relative; and changed the z-index of the .left to 3 (from 2) and changed the z-index of .right to 2 (from 3).

会给你你想要的我想。我添加了位置:相对;并将 .left 的 z-index 更改为 3(从 2)并将 .right 的 z-index 更改为 2(从 3)。

回答by Brian Behrend

z-indexhas no effect on elements that are not positioned (eg position:absolute;)

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

回答by Gelio

Use the positionproperty for element upper. Adding position:relativeto .left.

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

回答by BenB

Negative margin-left?

阴性margin-left

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