Home >Web Front-end >HTML Tutorial >How to clear float in html

How to clear float in html

coldplay.xixi
coldplay.xixiOriginal
2021-04-26 15:46:4215751browse

html Methods to clear floats: 1. Add height and width to the parent element of the floating element; 2. Add [overflow: hidden] to the parent element; 3. Add [clear: both] to the sibling element; 4. Use pseudo classes to remove floating.

How to clear float in html

The operating environment of this tutorial: windows7 system, html5 version, DELL G3 computer.

html Method to clear floating:

Method 1: (Give the width and height of the parent element)

Due to floating The element does not occupy the document flow, so the purple div disappears because there is no content to support the height, rather than disappearing. So the first method is to give the purple div height and width, that is, to the parent height and width of the floating element, so that it can expand the width and height by itself for display.

css code:

#div1{width:600px;height:300px;background: medium purple;}
 
#left{width: 200px;height: 100px;background: sky-blue;}
 
#right{width: 250px;height: 150px;background: pink;}

Rendering:

How to clear float in html

##Method 2: Parent element plus overflow: hidden

Many people will say that we don’t want to give the purple div a fixed width and height, but want its content to stretch it. Then we can add overflow:hidden to the css of the parent element, which is the purple div. This allows the purple div to be displayed.

css code:

#div1{background: medium purple;overflow:hidden}

Rendering

How to clear float in html

##Method 3: Add a clear to the sibling elements: both

In addition to changing the parent, we can also change the sibling elements of the child element to achieve the effect of removing floating.

html code:

<div id="div1">
    <div id="left"></div>
    <div id= "right"></div>
    <div id="div2"></div>
</div>

Rendering:

How to clear float in html##Method 4: Use pseudo-classes to remove floats

Use after when clearing floats with pseudo-classes, and add content: "" You can add content or not, but you must add display: block; and also write clear: both;

css code:

#div1:after{content:"";clear: both;display: block;}

Rendering:

How to clear float in htmlRelated learning recommendations:

html video tutorial

The above is the detailed content of How to clear float in html. 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