Three methods to enclose floating elements and three methods to enclose floating Elements
Html code
1 <body> 2 <section> 3 4 <p> image title </p> 5 </section> 6 <footer> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. </footer> 7 </body>
CSS code
1 p{ 2 margin:0; 3 } 4 img{ 5 float:left; 6 } 7 section{ 8 border:1px solid green; 9 margin:0 0 10px 0;10 }11 footer{12 background-color: #ccc;13 }
:
,
The following describes three methods to enclose floating elements. The final results are as follows:
Method 1: Add overflow: hidden to the parent Element
1 section{2 border:1px solid green; 3 margin:0 0 10px 0;4 overflow: hidden;5 }
// Overflow: the actual purpose of the hidden statement is 1. Prevent the contained elements from being extended by oversized content. After the application overflow: hidden, the contained elements keep their specific width, and the ultra-large sub-content is cut out by the container; 2. it reliably forces a parent element to include its floating child element.
Method 2: floating the parent element at the same time
1 section{ 2 border:1px solid green; 3 margin:0 0 10px 0; 4 width:100%; 5 float:left; 6 } 7 footer{ 8 background-color: #ccc; 9 clear:left;10 }
Method 3: add non-floating clear elements
Add a non-floating child element to the end of the parent element, and then clear the child element. There are two solutions.
First:
Simply add a child element to HTML and apply the clear attribute to it.
1 <body> 2 <section> 3 4 <p> image title </p> 5 <div class = "clear"> </div> 6 </section> 7 <footer> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </footer> 8 </body>
Here, a class is added for the div to facilitate style Writing in CSS.
1 div.clear{2 clear:left;3 }
Second:
If you do not particularly want to add this expressive element, there is a better way.
First, add a class clearfix for the section.
1 <section class = "clearfix"> 2 3 <p> image title </p> 4 </section> 5 <footer> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </footer>
Then, use this magic clearfix rule.
1 .clearfix:after{2 content:".";3 display:block;4 height:0;5 visibility:hidden;6 clear:both;7 }
// This clearfix rule was first invented by programmer Tony Aslett. It only adds a purge containing period as a non-floating element.