1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 2 <html lang="en"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 5 <title>test1</title> 6 <style type="text/css"> 7 #container { 8 background-color: #f1f1f1; 9 width: 80%;10 margin: 20px auto;11 }12 .item {13 float: left;14 color: white;15 text-shadow:0 1px black;16 margin: 10px 20px;17 padding: 20px;18 }19 #container > .item:nth-child(1) {20 background-color: #F00080;21 }22 #container > .item:nth-child(2) {23 background-color: #D8AAD8;24 }25 #container > .item:nth-child(3) {26 background-color: #A2aa5A;27 }28 #container > .item:nth-child(4) {29 background-color: #63B8FF;30 }31 </style>32 </head>33 <body>34 <div id="container">35 <div class="item">36 No.137 </div>38 <div class="item">39 No.240 </div>41 <div class="item">42 No.343 </div>44 <div class="item">45 INo.446 </div>47 </div>48 </body>49 </html>
Code running results:
us It was found that the parent element has no height at all (reviewing the element shows that the height of the parent element div#container = 0)
Analysis:
The floating float attribute will cause the element to break away from the current HTML document flow, then it will This makes: the current HTML document will be treated as if the element with the float attribute does not exist. Then, since these five child elements are all set to float, it can be regarded as that there is no content at all in the parent element #container. When there is no content, the div behaves exactly as height = 0.
Solution:
1. Set the parent element float
For example:
1 #container {2 background-color: #f1f1f1;3 width: 80%;4 margin: 20px auto;5 float: right;6 }
2. Add an empty div after the last child element that is set to float, and let This div clears float.
For example:
1 <div class="items"></div> 2 .items {clear: both;}
3. Set overflow:hidden for the parent element;
4. Do not use float, but use: for child elements display:inline-table or display:inline-block