当我将 float 添加到第一个元素时,它只是进入第二个 block 。这是什么原因?
检查这里的 fiddle : https://jsfiddle.net/peterzhong/33m7k5gy/9/
.container {
position:relative;
width:10em;
height:10em;
background:#aaa;
float:left;
}
.positioned {
position:absolute;
top:50%;
left:50%;
bottom:0;
right:0;
background:#FFA500;
}
.container1 {
position:relative;
width:10em;
height:10em;
background:#0092ff;
margin-top:100px;
}
.positioned1 {
position:absolute;
top:75%;
left:75%;
bottom:-3em;
right:-3em;
background:#FFA500;
}
<div class="container">
box1
<div class="positioned"></div>
</div>
<div class="container1">
box2
<div class="positioned1"></div>
</div>
最佳答案
根据您的目标,这里有两种不同的解决方案:
- 如果您愿意将两个容器分开放在不同的行中,您需要添加
clear: both
属性(property)<div class="container1">
所以它不会将表格左侧或右侧附加到任何floating
内容。
.container {
position:relative;
width:10em;
height:10em;
background:#aaa;
float:left;
}
.positioned {
position:absolute;
top:50%;
left:50%;
bottom:0;
right:0;
background:#FFA500;
}
.container1 {
position:relative;
width:10em;
height:10em;
background:#0092ff;
margin-top:100px;
clear: both; /*Add this property*/
}
.positioned1 {
position:absolute;
top:75%;
left:75%;
bottom:-3em;
right:-3em;
background:#FFA500;
}
<div class="container">
box1
<div class="positioned"></div>
</div>
<div class="container1">
box2
<div class="positioned1"></div>
</div>
- 如果您愿意将两个容器放在同一条线上但不相互重叠,则需要提供
<div class="container1">
一个float
也是属性(property)。
.container {
position:relative;
width:10em;
height:10em;
background:#aaa;
float:left;
}
.positioned {
position:absolute;
top:50%;
left:50%;
bottom:0;
right:0;
background:#FFA500;
}
.container1 {
position:relative;
width:10em;
height:10em;
background:#0092ff;
/*margin-top:100px;*/ /* Margin top removed to give both containers same height */
float: left; /* Add this property */
}
.positioned1 {
position:absolute;
top:75%;
left:75%;
bottom:-3em;
right:-3em;
background:#FFA500;
}
<div class="container">
box1
<div class="positioned"></div>
</div>
<div class="container1">
box2
<div class="positioned1"></div>
</div>
关于css - float 元素进入下一个框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37584902/