12.清除浮动.html 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. <style>
  8. /* .main {
  9. overflow: auto;
  10. } */
  11. #box1 {
  12. width: 200px;
  13. height: 200px;
  14. float: left;
  15. background-color: aqua;
  16. }
  17. #box2 {
  18. width: 200px;
  19. height: 200px;
  20. float: left;
  21. background-color: rgb(106, 0, 255);
  22. }
  23. #box3 {
  24. width: 200px;
  25. height: 200px;
  26. float: left;
  27. background-color: rgb(255, 111, 0);
  28. }
  29. #box4 {
  30. width: 200px;
  31. height: 200px;
  32. float: left;
  33. background-color: rgb(255, 0, 98);
  34. }
  35. /* #box5 {
  36. clear: both;
  37. } */
  38. .clearfix::after {
  39. content: "";
  40. display: block;
  41. clear: both;
  42. }
  43. </style>
  44. </head>
  45. <body>
  46. <!--
  47. 浮动会导致父元素高度塌陷
  48. 清除浮动办法:
  49. 1.溢出隐藏法
  50. 在父元素上添加overflow:hidden/auto
  51. 2.额外标签法:
  52. 在使用浮动的子集同级添加一个空标签 并给标签添加clear:both/left/right 属性
  53. 3.伪元素清浮动
  54. 在style中添加 .clearfix::after {
  55. content: "";
  56. display: block;
  57. clear: both;
  58. }
  59. 将clearfix添加到高度塌陷的父元素上
  60. -->
  61. <div class="main clearfix">
  62. <div id="box1">1</div>
  63. <div id="box2">2</div>
  64. <div id="box3">3</div>
  65. <div id="box4">4</div>
  66. <!-- <div id="box5"></div> -->
  67. </div>
  68. </body>
  69. </html>