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:
<div class="parent"> <div class="left">左侧区域</div> <div class="right">右侧区域</div> </div>
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 floatIn 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 floatsThis is a very common method. It uses the characteristics of empty labels to clear floats. The code is as follows: HTML:<div class="parent"> <div class="left">左侧区域</div> <div class="right">右侧区域</div> <div style="clear: both;"></div> </div>
.left { float: left; width: 300px; height: 100px; background-color: #ccc; } .right { float: right; width: 300px; height: 200px; background-color: #eee; }
clear:both to indicate the tag Clear float.
<div class="parent"> <div class="left">左侧区域</div> <div class="right">右侧区域</div> </div>
.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; }
content:"";display:block;clear :both; means adding a block-level element after the parent element and clearing the float.
<div class="parent"> <div class="left">左侧区域</div> <div class="right">右侧区域</div> </div>
.left { float: left; width: 300px; height: 100px; background-color: #ccc; } .right { float: right; width: 300px; height: 200px; background-color: #eee; } .parent { overflow: hidden; }
overflow:hidden on 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!