css.container{ margin: 30px auto; width:600px; height: 300px;
}.p{ border:solid 3px #a33;
}.c{ width: 100px; height: 100px; background-color: #060; margin: 10px; float: left;
} <div class="container"> <div class="p">
<div style="clear:both">//为什么不能写元素之前? <div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div style="clear:both">
</div>
</div>带有clear属性的元素为什么不能写浮动元素之前?
1 回答

人到中年有点甜
TA贡献1895条经验 获得超7个赞
在 css 文档里面规定 clear:both 的意思是:
要求框的顶边框边低于在源文档中之前生成的任何浮动框的底外边距边。
Requires that the top border edge of the box be below the bottom outer edge of any right-floating and left-floating boxes that resulted from elements earlier in the source document.
所以有 clear:both 属性的元素放在浮动元素之后才能起到闭合浮动的作用。
我一般清除浮动是通过浮动元素的父元素的伪元素实现的。在你这个例子中就是
.p:after{ clear:both; display:block; content:""; }
after 伪元素是父元素的最后一个子元素,所以能清除这个块里面的浮动。
添加回答
举报
0/150
提交
取消