Table of Contents
1 Floating brings layout convenience, but it also brings new problems
2 How to clear floats
2.1 Use the clear attribute to clear floats
2.1.1 Add an empty div to clean up the floats
2.1.2 Use CSS to insert elements
2.1.3 Master's handwriting
2.2.1 利用float来使父容器形成BFC
2.2.2 使用BFC的其它局限
2.2.3 hasLayout
3 一个相对靠谱的解决方案
4 最后
Home Web Front-end CSS Tutorial How to clear floats in CSS? Introduction to Clear and BFC methods

How to clear floats in CSS? Introduction to Clear and BFC methods

Nov 13, 2020 pm 05:35 PM
css clear float

How to clear floats in CSS? Introduction to Clear and BFC methods

[Recommended tutorial: CSS video tutorial]

The float attribute is often used in CSS layout, but after using the float attribute It is very distressing to make it separate from the parent container in the ordinary flow

1 Floating brings layout convenience, but it also brings new problems

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Clear float</title>
    <style type="text/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;
        }
    </style>
</head>
<body>
    <div>
        <div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
</body>
</html>
Copy after login

The effect we hope to see is this

But the result is like this

The parent container does not surround the floating child elements, commonly known as Collapse, in order to eliminate this phenomenon, we need some techniques to clear floats.

2 How to clear floats

There are generally two ideas for clearing floats

  • Use the clear attribute to clear floats

  • Make the parent container form a BFC

Look at it separately

2.1 Use the clear attribute to clear floats

What is the clear attribute? The clear attribute specifies which side of the element does not allow other previous floating elements. Modify the code just now

<div class="p">
    <div class="c"></div>
    <div class="c" style="clear:left;"></div>
    <div class="c"></div>
</div>
Copy after login

The second div is added After the clear:both attribute, the div on the left (the first div) no longer floats, so the subsequent divs can hang. We can use this to add an empty div at the end of the parent container and set the attribute clear:left, so that we can achieve our goal.

2.1.1 Add an empty div to clean up the floats

Slightly modify the code we just made

<div class="p">
    <div class="c"></div>
    <div class="c"></div>
    <div class="c"></div>
    <div style="clear:left;"></div>
</div>
Copy after login

That is, add

<div style="clear:left;"></div>
Copy after login

at the end of the parent container and take a look The effect

is really good. Some students may feel strange after reading it. Why did they want to modify the second div

<div class="c" style="clear:left;"></div>
Copy after login

in the previous example and it did not become Such an effect

# Let me tell you my humble opinion. The clear:left attribute only eliminates the impact of the floating div on the left side of it, but does not change the left div or even the Due to the performance of the parent container, from the perspective of the parent container, the three divs are still float, so the height is still collapsed. But we added a non-floating div at the end. Since it has the clear:left attribute, it will position itself according to the left p not floating, that is, it will be positioned to the next line, and the parent container will see a non-floating, The sub-element elements of the ordinary flow will surround them, which will have the effect of wrapping the three floating elements by the way, and the height will no longer collapse (I don’t know if this is explained clearly or if this understanding is correct, I hope you understand. guidance).

Of course, in addition to adding div, you can also add other html elements such as br. The principles are the same and will not be repeated.

2.1.2 Use CSS to insert elements

The above method has good browser compatibility, but there is a big problem in that it adds content to the page to achieve the purpose of changing the effect, that is Data and performance are confused. Since it is monetization, let’s see how to use CSS to solve this problem. The basic method is to append the element to the parent container at the end, but we can use the :after pseudo-element of CSS to do this.

Add a class floatfix

.floatfix:after{
    content:"."; 
    display:block; 
    height:0; 
    visibility:hidden; 
    clear:left;
}
Copy after login

Add this class to the parent container

<div class="p floatfix">
    <div class="c">1</div>
    <div class="c">2</div>
    <div class="c">3</div>
</div>
Copy after login

so that we can see the correct effect

To briefly explain, after adding the floatfix class to the parent container, an invisible block element will be appended to it, and then its clear attribute will be set to left, which is similar to the principle just now.

2.1.3 Master's handwriting

Nicolas Gallagher provides a cleaner-looking approach in A new micro clearfix hack

.floatfix:after{
    content:"";
    display:table;
    clear:both;
}
Copy after login

Nicolas Gallagher's original article also includes: before is to deal with margin overlap, which is not listed in this article.

Some classmates have proposed that the above method looks good, but what should we do if IE6 and 7 do not support pseudo elements? This requires us to use BFC/haslayout

2.2 Make the parent container form a BFC

After the indiscriminate bombardment about BFC in the garden a few days ago, I believe it Everyone has a certain understanding of BFC. Those who are not satisfied can take a look at Block Format Content. BFC has three characteristics

  • BFC会阻止垂直外边距(margin-top、margin-bottom)折叠

    按照BFC的定义,只有同属于一个BFC时,两个元素才有可能发生垂直Margin的重叠,这个包括相邻元素,嵌套元素,只要他们之间没有阻挡(例如边框,非空内容,padding等)就会发生margin重叠。

    因此要解决margin重叠问题,只要让它们不在同一个BFC就行了,但是对于两个相邻元素来说,意义不大,没有必要给它们加个外壳,但是对于嵌套元素来说就很有必要了,只要把父元素设为BFC就可以了。这样子元素的margin就不会和父元素的margin发生重叠了。

  • BFC不会重叠浮动元素
  • BFC可以包含浮动

我们可以利用BFC的第三条特性来“清浮动”,这里其实说清浮动已经不再合适,应该说包含浮动。也就是说只要父容器形成BFC就可以,简单看看如何形成BFC

  • floatleft|right
  • overflowhidden|auto|scroll
  • displaytable-cell|table-caption|inline-block
  • positionabsolute|fixed

我们可以对父容器添加这些属性来形成BFC达到“清浮动”效果

2.2.1 利用float来使父容器形成BFC

简单修改一下代码

<div class="p" style="float:left;">
    <div class="c">1</div>
    <div class="c">2</div>
    <div class="c">3</div>
</div>
Copy after login

这样我们可以得到结果

我们可以看到父容器高度没有塌陷,但是长度变短了,因为div应用float‘后会根据内容来改变长度,这个在很多时候很有用,但是我们不希望有这种效果怎么办?

2.2.2 使用BFC的其它局限

上面提到使用BFC使用float的时候会使父容器长度缩短,而且还有个重要缺陷——父容器float解决了其塌陷问题,那么父容器的父容器怎么办?难道要全部使用folat吗(确实有这种布局方式倒是)。BFC的几种方式都有各自的问题,overflow属性会影响滚动条和绝对定位的元素;position会改变元素的定位方式,这是我们不希望的,display这几种方式依然没有解决低版本IE问题。。。

看起来还是第一种方式比较好,可是低版本IE该怎么办呢?

2.2.3 hasLayout

我们知道在IE6、7内有个hasLayout的概念,很多bug正式由hasLayout导致的,当元素的hasLayout属性值为false的时候,元素的尺寸和位置由最近拥有布局的祖先元素控制。当元素的hasLayout属性值为true的时候会达到和BFC类似的效果,元素负责本身及其子元素的尺寸设置和定位。我们可以利用这点儿在IE6、7下完成清浮动,先看看怎么使元素hasLayout为true

  • position: absolute 
  • float: left|right
  • display: inline-block
  • width: 除 “auto” 外的任意值
  • height: 除 “auto” 外的任意值
  • zoom: 除 “normal” 外的任意值
  • writing-mode: tb-rl

在IE7中使用overflow: hidden|scroll|auto 也可以使hasLayout为true

3 一个相对靠谱的解决方案

经过上面的比较我们可以得出一个相对靠谱的解决方案

  • 在IE+、现代浏览器上使用伪元素
  • 在IE6、7使用hasLayout

具体应该使用哪种方式来使元素hasLayout为true呢?相对而言zoom:1比较好,因为不会造成其它影响。想造成只在IE6、7上使用某些CSS的效果,我们还得需要一些CSS hack的知识,感兴趣同学可以看看 CSS hack,我们可以写出这样的CSS

.floatfix{
    *zoom:1;
}
.floatfix:after{
    content:"";
    display:table;
    clear:both;
}
Copy after login

4 最后

虽然我们得出了一种浏览器兼容的靠谱解决方案,但这并不代表我们一定得用这种方式,很多时候我们的父容器本身需要position:absolute等形成了BFC的时候我们可以直接利用这些属性了,大家要掌握原理,活学活用。总而言之清理浮动两种方式

  • 利用 clear属性,清除浮动

  • 使父容器形成BFC

更多编程相关知识,请访问:编程学习网站!!

The above is the detailed content of How to clear floats in CSS? Introduction to Clear and BFC methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does placeholder mean in vue What does placeholder mean in vue May 07, 2024 am 09:57 AM

In Vue.js, the placeholder attribute specifies the placeholder text of the input element, which is displayed when the user has not entered content, provides input tips or examples, and improves form accessibility. Its usage is to set the placeholder attribute on the input element and customize the appearance using CSS. Best practices include being relevant to the input, being short and clear, avoiding default text, and considering accessibility.

What does span mean in js What does span mean in js May 06, 2024 am 11:42 AM

The span tag can add styles, attributes, or behaviors to text. It is used to: add styles, such as color and font size. Set attributes such as id, class, etc. Associated behaviors such as clicks, hovers, etc. Mark text for further processing or citation.

What does rem mean in js What does rem mean in js May 06, 2024 am 11:30 AM

REM in CSS is a relative unit relative to the font size of the root element (html). It has the following characteristics: relative to the root element font size, not affected by the parent element. When the root element's font size changes, elements using REM will adjust accordingly. Can be used with any CSS property. Advantages of using REM include: Responsiveness: Keep text readable on different devices and screen sizes. Consistency: Make sure font sizes are consistent throughout your website. Scalability: Easily change the global font size by adjusting the root element font size.

How to introduce images into vue How to introduce images into vue May 02, 2024 pm 10:48 PM

There are five ways to introduce images in Vue: through URL, require function, static file, v-bind directive and CSS background image. Dynamic images can be handled in Vue's computed properties or listeners, and bundled tools can be used to optimize image loading. Make sure the path is correct otherwise a loading error will appear.

What is the function of span tag What is the function of span tag Apr 30, 2024 pm 01:54 PM

The SPAN tag is an inline HTML tag that is used to highlight text by applying attributes such as style, color, and font size. This includes emphasizing text, grouping text, adding hover effects, and dynamically updating content. It is used by placing <span> and </span> tags around the text you want to emphasize, and is manipulated via CSS styling or JavaScript. The benefits of SPAN tags include semantic clarity, styling flexibility, and ease of maintenance.

How to wrap prompt in js How to wrap prompt in js May 01, 2024 am 06:24 AM

When using the prompt() method in JavaScript, you can achieve line breaks through the following three methods: 1. Insert the "\n" character at the position where you want to break the line; 2. Use the line break character in the prompt text; 3. Use CSS's "white" -space: pre" style forces line breaks.

What language is the browser plug-in written in? What language is the browser plug-in written in? May 08, 2024 pm 09:36 PM

Browser plug-ins are usually written in the following languages: Front-end languages: JavaScript, HTML, CSS Back-end languages: C++, Rust, WebAssembly Other languages: Python, Java

What is node in js What is node in js May 07, 2024 pm 09:06 PM

Nodes are entities in the JavaScript DOM that represent HTML elements. They represent a specific element in the page and can be used to access and manipulate that element. Common node types include element nodes, text nodes, comment nodes, and document nodes. Through DOM methods such as getElementById(), you can access nodes and operate on them, including modifying properties, adding/removing child nodes, inserting/replacing nodes, and cloning nodes. Node traversal helps navigate within the DOM structure. Nodes are useful for dynamically creating page content, event handling, animation, and data binding.

See all articles