search
HomeWeb Front-endCSS TutorialDetailed explanation of how to clear floats using CSS

This article mainly introduces the detailed method of using CSS to clear floats. It is worth noting that not simply clearing floats can solve related problems every time. The solution of closing floats mentioned at the end of the article is also worth a try. , Friends in need can refer to

Clear floating method
Method 1: Use an empty element with clear attribute

Use an empty element after the floating element, such as

, and assign the .clear{clear:both;} attribute in CSS to clear the float. You can also use
or
for cleaning.
.news {   
  background-color: gray;   
  border: solid 1px black;   
  }   

.news img {   
  float: left;   
  }   

.news p {   
  float: rightright;   
  }   

.clear {   
  clear: both;   
  }
<p class="news">
<img  src="/static/imghwm/default1.png"  data-src="news-pic.jpg"  class="lazy"   / alt="Detailed explanation of how to clear floats using CSS" >
<p>some text</p>
<p class="clear"></p>
</p>

Advantages: simple, less code, good browser compatibility.
Disadvantages: A large number of unsemantic html elements need to be added, the code is not elegant enough, and it is not easy to maintain later.

Method 2: Use the overflow attribute of CSS

Add overflow:hidden; or overflow:auto; to the container of the floating element to clear the float. In addition, in IE6 HasLayout needs to be triggered, such as setting the container width and height for the parent element or setting zoom:1. After adding the overflow attribute, the floating element returns to the container layer, raising the height of the container, achieving the effect of cleaning up the floating elements.

.news {   
  background-color: gray;   
  border: solid 1px black;   
  overflow: hidden;   
  *zoom: 1;   
  }   

.news img {   
  float: left;   
  }   

.news p {   
  float: rightright;   
  }
<p class="news">
<img  src="/static/imghwm/default1.png"  data-src="news-pic.jpg"  class="lazy"   / alt="Detailed explanation of how to clear floats using CSS" >
<p>some text</p>
</p>

Method 3: Add a float to the container of the floating element

Also add a floating attribute to the container of the floating element to clear the interior Float, but this will make it float as a whole and affect the layout, so it is not recommended.

Method 4: Use adjacent element processing

Do nothing and add the clear attribute to the element behind the floating element.

.news {   
  background-color: gray;   
  border: solid 1px black;   
  }   

.news img {   
  float: left;   
  }   

.news p {   
  float: rightright;   
  }   

.content{   
  clear:both;   
  }
<p class="news">
<img  src="/static/imghwm/default1.png"  data-src="news-pic.jpg"  class="lazy"   / alt="Detailed explanation of how to clear floats using CSS" >
<p>some text</p>
<p class="content">***</p>
</p>

Note that p.content here has content.

Method Five: Use CSS:after pseudo-element

Combined with:after pseudo-element (note that this is not a pseudo-class, but a pseudo-element, which represents the nearest element after elements) and IEhack, which are perfectly compatible with all major current mainstream browsers. IEhack here refers to triggering hasLayout.
Add a clearfix class to the container of floating elements, and then add an :after pseudo-element to this class to add an invisible block element (Block element) to the end of the element to clean up the floating elements.

.news {   
  background-color: gray;   
  border: solid 1px black;   
  }   

.news img {   
  float: left;   
  }   

.news p {   
  float: rightright;   
  }   

.clearfix:after{   
  content: "020";    
  display: block;    
  height: 0;    
  clear: both;    
  visibility: hidden;     
  }   

.clearfix {   
  /* 触发 hasLayout */
  zoom: 1;    
  }
<p class="news clearfix">
<img  src="/static/imghwm/default1.png"  data-src="news-pic.jpg"  class="lazy"   / alt="Detailed explanation of how to clear floats using CSS" >
<p>some text</p>
</p>

Add an invisible space "020" or dot "." at the end of the internal element of the container through CSS pseudo-elements, and assign the clear attribute to clear the float. It should be noted that for IE6 and IE7 browsers, a zoom:1; must be added to the clearfix class to trigger haslayout.

Summary
Through the above example, we can easily find that the methods of clearing floats can be divided into two categories:

One is to use the clear attribute, included in the floating element Add an empty p with the clear: both attribute at the end to close the element. In fact, the method of using the :after pseudo-element is also achieved by adding an element with the content of a dot and the clear: both attribute at the end of the element.

The second is to trigger the BFC (Block Formatting Contexts, block-level formatting context) of the parent element of the floating element, so that the parent element can contain floating elements. Regarding this point.

Use the :after pseudo-element method in the main layout of the web page and use it as the main way to clean up floats; use overflow:hidden; in small modules such as ul (pay attention to possible hidden overflow element problems); if it is a float itself Elements can automatically clear internal floats without special processing; use adjacent elements in the body to clear previous floats.

Finally, you can use the relatively perfect :after pseudo-element method to clean up the floats, making the document structure clearer.

Postscript: Clear float or close float?
We often use floats in web page layout. With it, we can more easily achieve the effects we want, but floats often leave some hidden dangers. At this time, we usually do one thing to clear the floats, but clearing the floats often leaves hidden dangers. The following code:

<!DOCTYPE html>   
<html>   
<head>   
    <meta charset="UTF-8">   
    <title>Document</title>   
    <style type=&#39;text/css&#39;>   
        #main{   
            border: 1px solid #000;   
        }   
        #left{   
            float: left;   
            width: 100px;   
            height: 100px;   
            background-color: #f00;   
        }   
        #right{   
            float: left;   
            width: 100px;   
            height: 100px;   
            background-color: #0f0;   
        }   
    </style>   
</head>   
<body>   
    <p id="main">   
        <p id="left"></p>   
        <p id="right"></p>   
    </p>   
</body>   
</html>

The rendering is as follows:
Detailed explanation of how to clear floats using CSS

Although clear:both is used in foot to clear floats, the height of main cannot adapt to the height of sub-elements, resulting in collapse (pointed by the arrow).

The following introduces closed float. As the name suggests, it is to close the floating element and clear the impact of floating. Currently, the most commonly used method to clear floats is clearfix. Specifically, there is no need to add clear:both in the foot, insert the following line of css:

#main:after{   
            content: &#39;.&#39;;   
            height: 0;   
            visibility: hidden;   
            /*display: block;*/
            clear:both;   
        }

The above is the detailed content of Detailed explanation of how to clear floats using CSS. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How much specificity do @rules have, like @keyframes and @media?How much specificity do @rules have, like @keyframes and @media?Apr 18, 2025 am 11:34 AM

I got this question the other day. My first thought is: weird question! Specificity is about selectors, and at-rules are not selectors, so... irrelevant?

Can you nest @media and @support queries?Can you nest @media and @support queries?Apr 18, 2025 am 11:32 AM

Yes, you can, and it doesn't really matter in what order. A CSS preprocessor is not required. It works in regular CSS.

Quick Gulp Cache BustingQuick Gulp Cache BustingApr 18, 2025 am 11:23 AM

You should for sure be setting far-out cache headers on your assets like CSS and JavaScript (and images and fonts and whatever else). That tells the browser

In Search of a Stack That Monitors the Quality and Complexity of CSSIn Search of a Stack That Monitors the Quality and Complexity of CSSApr 18, 2025 am 11:22 AM

Many developers write about how to maintain a CSS codebase, yet not a lot of them write about how they measure the quality of that codebase. Sure, we have

Datalist is for suggesting values without enforcing valuesDatalist is for suggesting values without enforcing valuesApr 18, 2025 am 11:08 AM

Have you ever had a form that needed to accept a short, arbitrary bit of text? Like a name or whatever. That's exactly what is for. There are lots of

Front Conference in ZürichFront Conference in ZürichApr 18, 2025 am 11:03 AM

I'm so excited to be heading to Zürich, Switzerland for Front Conference (Love that name and URL!). I've never been to Switzerland before, so I'm excited

Building a Full-Stack Serverless Application with Cloudflare WorkersBuilding a Full-Stack Serverless Application with Cloudflare WorkersApr 18, 2025 am 10:58 AM

One of my favorite developments in software development has been the advent of serverless. As a developer who has a tendency to get bogged down in the details

Creating Dynamic Routes in a Nuxt ApplicationCreating Dynamic Routes in a Nuxt ApplicationApr 18, 2025 am 10:53 AM

In this post, we’ll be using an ecommerce store demo I built and deployed to Netlify to show how we can make dynamic routes for incoming data. It’s a fairly

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor