First paste a common floating code parent element Div set the background color to gray # f1f1f1, child element Div respectively set different colors
<! Doctype HTML public "-// W3C // dtd html 4.01 // en" "http://www.w3.org/TR/html4/strict.dtd">
<HTML lang = "en">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> test1 </title>
<Style type = "text/CSS">
# Container {
Background-color: # f1f1f1;
Width: 80%;
Margin: 20px auto;
}
. Item {
Float: left;
Color: white;
Text-Shadow: 0 1px black;
Margin: 10px 20px;
Padding: 20px;
}
# Container>. Item: Nth-Child (1 ){
Background-color: # f08080;
}
# Container>. Item: Nth-child (2 ){
Background-color: # d8bfd8;
}
# Container>. Item: Nth-child (3 ){
Background-color: # a2cd5a;
}
# Container>. Item: Nth-child (4 ){
Background-color: # 63b8ff;
}
</Style>
</Head>
<Body>
<Div id = "Container">
<Div class = "item">
I am No.1
</Div>
<Div class = "item">
I am no. 2
</Div>
<Div class = "item">
I am No. 3
</Div>
<Div class = "item">
I am No. 4
</Div>
</Div>
</Body>
</Html>
This code will generate the following results:
We found that the parent element has no height at all (the review element shows that the parent element Div # container height = 0)
Analysis:
The floating float attribute disconnects the element from the current HTML document stream, so that the current HTML document does not exist as the element that sets the float attribute. Therefore, because float is set for all the five child elements, it can be viewed as the parent element # There is no content in the container. When there is no content in the DIV, the height is equal to 0.
Solution:
1. Set the parent element float
For example:
# Container {
Background-color: # f1f1f1;
Width: 80%;
Margin: 20px auto;
Float: right;
} In this way, the parent element is also out of the current document stream. The child element and the parent element are separated, and the child element is still in the parent element. The content of the parent element is not empty, therefore, the height will adapt to the height of the child element.
2. Add an empty Div after the last child element with floating settings and clear the floating Div.
For example, <Div class = "items"> </div>
. Items {clear: Both ;}
3. Set overflow: hidden for the parent element;
4. Do not use float. Instead, use the following sub-elements: Display: inline-table or display: inline-block.
The effects of these methods are as follows: