清除浮动

一个误区

<div class="left">左侧</div>
<div class="right">右侧</div>
<div class="bottom">底部</div>
.left {
  float: left;
  width: 1000px;
  height: 600px;
  background: bisque;
}
.right {
  float: right;
  width: 600px;
  height: 200px;
  background: deeppink;
}
.bottom {
  float: left;
  width: 500px;
  height: 50px;
  background: mediumaquamarine;
}

此时由于没有清除浮动,bottom 是这样的:

这里写图片描述

清除浮动可以为bottom增加 clear:both 属性来实现

.bottom {
  clear: both;
  float: left;
  width: 500px;
  height: 50px;
  background: mediumaquamarine;
}

这里写图片描述

注意,我一直有个误区,不可以通过 right:after 或者 bottom:before 来实现,因为 :after:before 是在元素内部增加一个伪元素,相当于增加了一个子元素,而不是兄弟元素

比如,给 right 增加一个伪元素,实际上是增加的子元素,在 right 内部

这里写图片描述

正确用法

所以对于父元素坍塌的情况可以使用伪元素来清除浮动

<div class="outer">
  <div class="left">左侧</div>
  <div class="right">右侧</div>
</div>
<div class="bottom">底部</div>
.outer {
  background: gray;
}
.left {
  float: left;
  width: 1000px;
  height: 600px;
  background: bisque;
}
.right {
  float: right;
  width: 600px;
  height: 200px;
  background: deeppink;
}
.bottom {
  width: 1500px;
  height: 50px;
  background: mediumaquamarine;
}

这里写图片描述

可以看到,由于没有清除浮动,虽然 bottom 在 outer 外部,却没位于底端,因为 outer 内部子元素为 float,导致 outer 并没有被撑开。

解决这个问题有三种方法
1. 给 bottom 添加 clear:both
2. 给 outer 添加 overflow:hidden
3. 利用伪元素添加 clear:both

原理都是为了形成 BFC, 注意,clear 属性只适用于块级元素

所以给 outer 添加一个 clear-fix

.clear-fix:after {
  display: block;
  content: '';
  clear: both;
}

问题解决

这里写图片描述

参考

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值