0
点赞
收藏
分享

微信扫一扫

清除浮动的方法

Star英 2022-02-01 阅读 137

浮动副作用介绍:

<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属性
<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

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

<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>

在这里插入图片描述

举报

相关推荐

0 条评论