We have:
- parent block
- floating block nested in parent block
- text (or block, or whatever) that will flow around the floating block (needed for the demonstration)
HTML
2 | This block with float: left; |
3 | text that will set the height of the parent |
five | This is the next block in the general stream. |
Questions:
- What height in this case will have a parent block (div class = "parent")?
- where is the block (div class = "nextStaticBlock") located under the parent block?
The correct answers in the picture:
it was expected that the next block would be located under the parent block whose height would be equal to the height of the tallest subsidiary block (in this example, the height of the floating block)
|
in reality, the next block (in most browsers) is actually located under the parent block, but the height of the parent is equal to the height of the static (non-floating) content
|
Old solution
We clear the stream using an additional element placed at the end of the parent block with the property or attribute clear (
<div style = "clear: both;> or
):
HTML
one | <div class = "parent"> |
2 | <div class = "floatBlock"> This block with float: left; </ div> |
3 | text that will set the height of the parent |
four | <div style = "clear: both;"> </ div> |
6 | <div class = "nextStaticBlock"> This is the next block in the general stream </ div> |
The disadvantage of this method is that the useless element appears, which damages the structure and semantics of the code element. Often with a single purpose is to clear the stream.
New solution
Clear the stream using the pseudo-element: after
HTML
one | <div class = "parent"> |
2 | <div class = "floatBlock"> This block with float: left; </ div> |
3 | text that will set the height of the parent |
five | <div class = "nextStaticBlock"> This is the next block in the general stream </ div> |
CSS:
CSS
- to hide the point it is better to use visibility: hidden instead of overflow: hidden, since In some browsers, the point is still visible.
and for IE we connect conditional comments (recommended) or using hacks (not recommended)
CSS
2 | zoom: 1; / * set hasLayout * / |
3 | display: block; / * resets display for IE / Win * / |
or simply
.clearfix: after {
visibility: hidden;
display: block;
font-size: 0;
content: "";
clear: both;
height: 0;
}
Clear the overflow: hidden stream
There is also a better way to clear the stream - add an overflow: hidden rule to the parent that contains floating elements:
CSS
3 | zoom: 1; / * for IE * / |
Demo example. The method is simpler, but not always applicable (for example, when the parent contains absolutely positioned elements that should go beyond the boundaries of the parent. Example - drop-down menu).
Micro clearfix
If IE6-7 support is not needed:
CSS
If necessary, then it is safer to use this option:
CSS
01 | / * For modern browsers * / |
Comments
To leave a comment
Cascading CSS / CSS3 Style Sheets
Terms: Cascading CSS / CSS3 Style Sheets