清除浮动

清除浮动

清除浮动,预防高度塌陷。

举例:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>test</title>
  <style>
    .container {
      background-color: gray;
    }

	.float-left {
      float: left;
    }

    .float-right {
      float: right;
    }
  </style>
</head>

<body>
  <div class="container">
    <p class="float-left">
      For UI components, we don't recommend aiming for complete line-based coverage, because it
      leads to too much focus on the internal implementation details of the components and could result in brittle
      tests.
    </p>
    <p class="float-right">
      Instead, we recommend writing tests that assert your component's public interface, and treat its internals as a
      black box. A single test case would assert that some input (user interaction or change of props) provided to the
      component results in the expected output (render result or emitted custom events).
    </p>
  </div>
</body>

</html>

div.container元素因为子元素浮动导致高度塌陷了,height为0。

清除浮动的方法:

一、在父元素的最后添加一个空标签
	<div style="clear:both"></div>

缺点:添加了一个无意义的标签,违背了我们结构与样式分离的web精髓。

二、父元素添加overflow的样式
.container{
	overflow:auto; // 或 overflow:hidden;
	background-color: gray;
}

添加overflow属性,元素又会回到容器中,把容器高度给撑起来,达到清除浮动的效果。

三、让父元素也跟着浮动
.container{
  float:left;
}

给浮动元素添加浮动属性,就会达到清除内部浮动的效果。

缺点:父元素浮动了,会影响整个页面的布局,若父元素外面还有一个包裹它的元素呢?

四、给父元素使用after的伪元素

给div.container添加一个clearfix类。

  1. display:block;

    .clearfix:after { /* clear:both用来清除浮动,其余属性都是用来隐藏元素*/
      content: ' '; /* 加一段内容 */
      display: block; /* 让生成的元素以块级形式显示,占满空间 */
      height: 0; /* 避免生成的内容破环原有高度 */
      clear: both; /* 清除左右两边浮动 */
      visibility: hidden; /* 让生成的内容不可见  */
    }
    
    .clearfix {
      *zoom: 1; /* 为IE6、IE7浏览器的兼容性而设置(不支持伪类),zoom属性促发haslayout,才能清除浮动  */
    }
    
  2. display:table;

    .clearfix:before, /* 添加before伪类,防止顶部空白崩溃(margin的叠加) */
    .clearfix:after {
      content: ' ';
      display: table;  /* 创建一个匿名的表格单元,促发BFC */
    }
    
    .clearfix:after {
      clear: both; /* 清除左右两边浮动 */
    }
    

总结:促发BFC就可以清除浮动。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值