[css] Three ways to clear floats in css

Summary of three methods for clearing floats in css

Instructions for use

CSS Float will move an element to the left or right, and its surrounding elements will also be rearranged.
Floating elements will break away from the document flow and float left/right until they encounter the parent element or another floating element. Floating elements will cause the height of the parent element to collapse, causing the following inline elements to be arranged around it. The block element immediately following it will be overwritten, so in order to avoid the above situation, as long as the element uses float, the float must be cleared.

<div class="main">
  <div class="mainLeft">200px*200px</div>
</div>

<!-- css -->
<style>
.main {
      
      
  background-color: #ccc;
}
.mainLeft {
      
      
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
  float: left;
  background-color: #ff0000;
}
</style>

floating elements

Insert image description here
After clearing floats,
Insert image description here
the following will introduce three commonly used methods to clear floats:

Method 1: Add overflow:hidden style to the parent element (not recommended)

<!-- css -->
<style>
.main {
      
      
  background-color: #ccc;
  overflow: hidden;
}
.mainLeft {
      
      
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
  float: left;
  background-color: #ff0000;
}
</style>

Method 2: Add an empty element after the floating element, and set the clear attribute in CSS to clear the floating element.

<div class="main">
  <div class="mainLeft">200px*200px</div>
  <div class="mainBlack"></div>
</div>

<!-- css -->
<style>
.main {
      
      
  background-color: #ccc;
}
.mainLeft {
      
      
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
  float: left;
  background-color: #ff0000;
}
.mainBlack {
      
      
  clear: both;
}
</style>

Method 3: Use pseudo element: after (recommended)

Add a pseudo element to the parent element that uses floating elements , and then set the clear attribute to the pseudo element. Generally, this method is used in a public style file. When encountering elements that need to be floated in the future, directly add the corresponding className. Can

<div class="main clearfloat">
  <div class="mainLeft">200px*200px</div>
  <div class="mainBlack"></div>
</div>

<!-- css -->
<style>
.main {
      
      
  background-color: #ccc;
}
.mainLeft {
      
      
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
  float: left;
  background-color: #ff0000;
}
.clearfloat::after {
      
      
  display: block;
  width: 0;
  height: 0;
  content: "";
  overflow: hidden;
  clear: both;
}
</style>

The above is my personal experience, I hope it will be helpful to everyone!

Guess you like

Origin blog.csdn.net/weixin_44490021/article/details/132018534