Home>Article>Web Front-end> css clear float
CSS Tips Clearfix
Floating is a very important layout technology in CSS and is widely used in web page layout. But it will also cause some problems, such as the height collapse of the parent element. Clearfix technology was created to solve this problem. This article will introduce several common methods of clearing floats.
1. The problem of floating
First, let’s understand the problem of floating.
HTML:
左侧区域右侧区域
CSS:
.left { float: left; width: 300px; height: 100px; background-color: #ccc; } .right { float: right; width: 300px; height: 200px; background-color: #eee; }
The effect is as shown below:
##You can see, left Both the side area and the right area use floating technology. But if we want the height of the parent element (i.e. .parent) to be equal to the height of the child element, then the following problems will occur: As you can see, the height of the parent element Significantly smaller. This is because the child elements use floating, so they are out of the document flow, and the parent element does not contain them, causing them to not be included in the height calculation. 2. Several methods of clearing float In order to solve this problem, we need to let the parent element recalculate the height by clearing the float. Here are some commonly used methods to clear floats: 1. Use empty labels to clear floats This is a very common method. It uses the characteristics of empty labels to clear floats. The code is as follows: HTML:CSS:左侧区域右侧区域
.left { float: left; width: 300px; height: 100px; background-color: #ccc; } .right { float: right; width: 300px; height: 200px; background-color: #eee; }Add an empty tag at the end of the parent element and set
clear:bothto indicate the tag Clear float.
CSS:左侧区域右侧区域
.left { float: left; width: 300px; height: 100px; background-color: #ccc; } .right { float: right; width: 300px; height: 200px; background-color: #eee; } .parent::after { content: ""; display: block; clear: both; }Use the ::after pseudo-element on the parent element and set
content:"";display:block;clear :both;means adding a block-level element after the parent element and clearing the float.
CSS:左侧区域右侧区域
.left { float: left; width: 300px; height: 100px; background-color: #ccc; } .right { float: right; width: 300px; height: 200px; background-color: #eee; } .parent { overflow: hidden; }Set
overflow:hiddenon the parent element, at this time , the parent element forms a BFC so that the floating elements can be included correctly.
The above is the detailed content of css clear float. For more information, please follow other related articles on the PHP Chinese website!