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;
}
<p class="container">
<p class="p">
<p style="clear:both">//为什么不能写元素之前?
<p class="c"></p>
<p class="c"></p>
<p class="c"></p>
<p style="clear:both">
</p>
</p>
Why can’t elements with clear attributes be written before floating elements?
If the element with the clear attribute is written before the floating element, then there are no floating elements on both sides of it, so this attribute has no effect
In the css document, clear:both means:
So elements with the clear:both attribute can be placed after floating elements to close the float.
I usually clear floats through the pseudo-element of the parent element of the floated element. In your case it is
The after pseudo-element is the last child element of the parent element, so it can clear the float in this block.
Let’s first understand the impact of float and the role of clear. Write more demos and feel them, and you will know where to put them. See more documents and more Baidu
clear:both; To be written after the floating element, clear the floating element.
Let me talk about my understanding
clearboth is for itself
So <p style="clear:both"/> means clearing the left and right floats of this element. If it is placed in front, the last floated element will still affect the parent Element
For
clear
属性一定要牢记的是:1) 该属性是针对元素本身的,比如说 A B C 三个浮动元素,想要清除C元素左边的浮动,则是将
clear
acting on C, it is written:Is that okay? The answer is no. Because
clear
can only clear the previous float of this element."clear on an element only clears the floats before it in document order. It doesn't clear floats after it."
2) There are many ways to clear floats, but the most common and most optimized one is to use pseudo elements: