Blogger Information
Blog 28
fans 0
comment 1
visits 21323
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
浮动元素高度塌陷产生的原因与解决方案
南宫
Original
741 people have browsed it

原因:

元素浮动后,就不在整个文档流的管辖范围,那么它之前存在在父元素内的高度就随着浮动不复存在了,而此时父元素会默认自己里面没有任何内容。

解决方案

  1. <div class="container">
  2. <div class="item">1</div>
  3. <div class="item">2</div>
  4. <div class="item">3</div>
  5. </div>

伪元素解决:

  1. .container {
  2. border: 3px dashed red;
  3. }
  4. .item {
  5. width: 150px;
  6. height: 150px;
  7. }
  8. .item:first-of-type {
  9. background-color: lightgreen;
  10. }
  11. .item:nth-last-of-type(2) {
  12. background-color: lightcoral;
  13. }
  14. .item:last-of-type {
  15. background-color: lightskyblue;
  16. }
  17. .item {
  18. float: left;
  19. }
  20. .container::after {
  21. content: "";
  22. display: block;
  23. clear: both;
  24. }

最简单的解决方案,用到BFC(块级格式化上下文):

  1. .container {
  2. border: 3px dashed red;
  3. }
  4. .item {
  5. width: 150px;
  6. height: 150px;
  7. }
  8. .item:first-of-type {
  9. background-color: lightgreen;
  10. }
  11. .item:nth-last-of-type(2) {
  12. background-color: lightcoral;
  13. }
  14. .item:last-of-type {
  15. background-color: lightskyblue;
  16. }
  17. .item {
  18. float: left;
  19. }
  20. /* .container::after {
  21. content: "";
  22. display: block;
  23. clear: both;
  24. } */
  25. .container {
  26. overflow: auto;
  27. }
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:元素浮动后, 其实只是半脱离文档流, 仍然受到浮动元素前面元素的影响 , 它也只是影响到了它后面元素的排列而已
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post