css防止浮动元素父元素高度塌陷的三个方法

来源:互联网 发布:sql视图更新 编辑:程序博客网 时间:2024/04/30 15:14
<style>
  .div1{
   background-color:yellow;
   
   width:330px;
  }
  .div2{
   background-color:red;
   height:300px;
   width:300px;
   float:left;
  }
</style>
</head>
<body>
 <div class="div1">
  <div class="div2"></div>
  <div class="div3"></div>
 </div>
</body>
此时防止父元素高度塌陷的方法:
1,在div2后面追加div3,并设置属性为
.div3{
   clear:both;
   height:0;   
   overflow:hidden;
  }
此时父元素宽度为设置的330px,若不设置,则充满整行。测试的不设置height:0;和overflow:hidden;也是可以的。

2,设置父元素也为浮动

3,使用clearfix
.clearfix:after{
   content:"";
   display:block;
   clear:both;
   height:0;
  }
  .clearfix{
   zoom:1;
   width:330px;
  }
此时父元素的宽度由。clearfix设置的决定,弱国没有设置,则为.div1下设置的,如果都没有设置则充满整行。
0 0