div.box{
width:105px;
height:200px;
border:1px solid red;
}
div.box1{
float:left;
width:50px;
height:50px;
border:1px solid red;
}
div.box2{
float:left;
width:50px;
height:50px;
border:1px solid red;
}
div.box3{
width:100px;
clear:both;
margin-top:20px;
height:50px;
border:1px solid red;
}
<body>
<div class="box">
<div class="box1">box1</div>
<div class="box2">box2</div>
<div class="box3">box3</div>
</div>
</body>
box1 和 box2 都向左浮动,而在 box3 的 css 中,它们都被清除了。
现在 box1 和 box2 在 box3 的顶部,我想在 div.box3 的 css 中用 margin-top:20px;
在 box3 上插入边距空间。
为什么margin-top能起作用?
我已经接受了Narxx的答案,一些事实让我取消它作为最佳答案,真实网页中有很多元素要 float ,很多网页长达3000行或更多, float 框太多,我们不得不wrapp all the floated box when to clear the floating effect with the css code.
如果有10个地方要清除 float ,下面的css代码要写10次,加上10个容器来装盒子,很繁琐,如何简化操作?
div.container:after{
clear:both;
display:block;
content:"";
}
也许 luboskrnac 的方法更好。
最佳答案
clear
应该用在两个 float 元素下的 div
中,但不能用在 box3
中。 清除
"specifies whether an element can be next to floating elements that precede it or must be moved down (cleared) below them' .
您可以添加一个 div
来clear: both;
(向下移动所有内容),这样它将在 float 元素之后向下移动所有内容
CSS:
.box{
width:105px;
height:200px;
border:1px solid red;
}
.box1{
float:left;
width:50px;
height:50px;
border:1px solid red;
}
.box2{
float:left;
width:50px;
height:50px;
border:1px solid red;
}
.box3{
width:100px;
margin-top:20px;
height:50px;
border:1px solid red;
}
.clearfix {
clear: both;
}
html
<div class="box">
<div class="box1">box1</div>
<div class="box2">box2</div>
<div class="clearfix"></div>
<div class="box3">box3</div>
</div>
关于html - 为什么 margin-top 可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36966162/