清除浮动的方式

1. 给父级定义height

.parent {
    background-color: red;
}
.float-left {
    width: 200px;
    height: 200px;
    float: left;
}
<div class="parent">
      <div class="float-left"></div>
</div>

2. 在结尾处添加空div,样式设置为clear: both

.parent {
    background-color: red;
}
.float-left {
    width: 200px;
    height: 200px;
    float: left; //这里clear的作用是清除浮动,它需要跟在浮动元素的后面
}
    <div class="parent">
        <div class="float-left"></div>
        <div style="clear: right"></div>
        <!-- 这里clear的作用是清除浮动,它需要跟在浮动元素的后面,left为清除左浮动,right为清除右浮动,both为清除全部 -->
    </div>

3. 父级定义伪类

"clearfloat"是父容器的class名称,“content:” ";"是在父容器的结尾处放一个空白字符,"height:0;"是让这个这个空白字符不显示出来,"display: block; clear: both;"是确保这个空白字符是非浮动的独立区块。但是,:after选择符IE 6不支持,也就是说上面的这段代码在IE 6中无效,这怎么办? 我们添加一条IE6的独有命令"zoom:1;"就行了,这条命令的作用是激活父元素的"hasLayout"属性,让父元素拥有自己的布局。IE 6会读取这条命令,其他浏览器则会直接忽略它。

.parent {
    background-color: red;
}
.float-left {
    width: 200px;
    height: 200px;
    float: left;
}
.clearfloat:after {
    display: block;
    clear: both;
    content: '';
    visibility: hidden;
    height: 0;
    zoom: 1;
}
<div class="parent clearfloat">
    <div class="float-left"></div>
</div>

4. 把父级变成BFC

生成BFC的条件

  1. 根元素
  2. float的值不为none
  3. overflow的值不为visible
  4. display的值为inline-block、table-cell、table-caption
  5. column-span: all
  6. position的值为absolute或fixed
  7. 弹性盒(flex或inline-flex)
  8. display: flow-root
.parent {
    background-color: red;
    float: left;
}
.parent {
    background-color: red;
    overflow: hidden;
}
.parent {
    background-color: red;
    display: table-cell;
}
.parent {
    background-color: red;
   	position: absolute;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值