博客列表 >浮动元素高度塌陷产生的原因与解决方案

浮动元素高度塌陷产生的原因与解决方案

南宫
南宫原创
2020年06月27日 17:29:45750浏览

原因:

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

解决方案

  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. }
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议