Html 强制 Div 低于另一个并防止重叠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14116569/
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 04:40:31  来源:igfitidea点击:

Force Div below another and prevent overlap

csslayouthtml

提问by Passerby

I have two Div elements. The first should be 100% height and width of the screen. I would like the second Div to be 100% width but variable height depending on the contents and to start inline (below the first). So the full screen is Div 1 and you have to scroll down to see Div 2. But everything I have tried they overlap.

我有两个 Div 元素。第一个应该是屏幕的 100% 高度和宽度。我希望第二个 Div 为 100% 宽度但高度可变,具体取决于内容并开始内联(在第一个下方)。所以全屏是 Div 1,你必须向下滚动才能看到 Div 2。但是我尝试过的所有内容都重叠了。

<div style="background-color:red;height:100%;width:100%;left:0px;top:0px"></div>
<br/>
<div style="width:100%;position:relative;background-color:yellow">
      <br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>..
</div>

? http://jsfiddle.net/FBJ8h/

? http://jsfiddle.net/FBJ8h/

回答by Passerby

Becasue

因为

position:absolute

makes the div non-occupy, which means other elements don't "see" them when aligning and positioning.

使 div 不被占用,这意味着其他元素在对齐和定位时不会“看到”它们。

Use this:

用这个:

html,body {
    height:100%;
}
div.div2 {
    top:100%;
}

JSFiddle

JSFiddle

回答by atreju

First you have to set the html- and body-tag to height: 100%:

首先,您必须将 html- 和 body-tag 设置为高度:100%:

html, body {
    height:100%;
}

And the second thing, you have to change is to set the position of the first div to "relative" and not to "absolute" (as it is in the jsfiddle-file):

第二件事,你必须改变的是将第一个 div 的位置设置为“相对”而不是“绝对”(就像在 jsfiddle 文件中一样):

position: relative;

I hope it helps...

我希望它有帮助...

EDIT: And remove the <br>-Tag between the two divs - if not, there will be a white gap between them...

编辑:并删除<br>两个 div 之间的 -Tag - 如果没有,它们之间会有一个白色间隙......

回答by Vignesh Veeran

Use should use "clear:both" ... add the following between the div tags

使用应使用“clear:both”...在 div 标签之间添加以下内容

<style>
.clearfix{
clear:both;
}
</style>
<body>
<div class="clearfix"></div>
<body>