清除浮动的方法

浮动副作用介绍:

<div style="width: 250px; background: blue;">
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
</div>

上面是带有浮动效果的代码。行内块元素使用浮动消除了水平间隙,所以行内块元素总长度200px,高度都是50px。父元素宽度250px,高度由子元素决定,为50px。预计效果和实际效果分别如下图:

在这里插入图片描述

在这里插入图片描述

这种情况的原因是浮动元素脱离文档流(但不脱离文本流),宽度和高度将不会对其它元素造成影响,因此上述示例父元素高度不会受子元素影响,父元素最后的实际尺寸是250×0

消除浮动的方法:

  1. 在非浮动元素上使用clear属性
  1. clear属性通常取值为both或right或left
  2. clear属性通常设置在子元素中,情景是一个父元素作为容器,里面若干子元素中存在浮动的子元素
  3. clear属性的取值含义是,在物理位置上,当前元素在左边或右边或左右两边都不允许有浮动元素,可以参考<<精通CSS>>里面有介绍具体计算过程
  4. clear属性的效果,会把浮动元素顶到父元素的顶部
<div style="width: 250px; background: blue;">
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
    <div style="clear: left;"></div>
</div>

可以用JavaScript动态插入,可以直接如上设置一个非浮动元素,也可以使用伪元素

在这里插入图片描述

  1. 在浮动元素的父元素上开启BFC

在父元素内部开启BFC的方法有:

  1. 父元素的overflow属性不是visible,通常设置为auto
  2. 父元素的float属性不是none
  3. 父元素的position属性不是relative和static
  4. 父元素的display为inline-block或table-cell或table-caption

举例而言,就拿第一个方案说明

<div style="width: 250px; background: blue; overflow: auto;">
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
    <div style="width: 50px; height: 50px; background: red; display: inline-block; float: left;"></div>
</div>

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vanghua

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值