清除浮动的几种常用方式

129 阅读1分钟

在父级div添加after伪类或者zoom:1

ie8以上及其他浏览器可以使用after伪类,低版本ie使用zoom:1清除浮动

比较推荐的一种方式

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>无标题文档</title>
    <style type="text/css">
        .div1,
        .div2,
        .div3
        {
            width: 100px;
            height: 100px;
        }

        .div1 {
            background-color: red;
        }

        .div2 {
            background-color: blue;
            float: left;
        }

        .div3 {
            background-color: yellow;
        }

        /*清除浮动代码*/
        .parentDiv:after {
            display: block;
            clear: both;
            content: "";
            visibility: hidden;
            height: 0
        }
    </style>
</head>
<body>
<div class="parentDiv">
    <div class="div1"></div>
    <div class="div2"></div>
</div>
<div class="div3"></div>
</body>
</html>

浮动元素后面新增div元素,并添加clear:both属性

这是以前比较推荐的一种清除浮动的方式,由于需要增加新的标签比较麻烦,不是很推荐使用这种方式

 <style type="text/css">
        .div1,
        .div2,
        .div3
        {
            width: 100px;
            height: 100px;
        }
        .div1 {
            background-color: red;
        }
        .div2 {
            background-color: blue;
            float: left;
        }
        .div3 {
            background-color: yellow;
        }
        .div2clear{
          clear: both;
        }
        .div2
    </style>


    <div class="div1"></div>
    <div class="div2"></div>
    <div class="div2clear"></div>
    <div class="div3"></div>

给父级元素添加overflow:hidden

注意:必须给父级元素宽度或者zoom:1设置

<style type="text/css">
        .div1,
        .div2,
        .div3 {
            width: 100px;
            height: 100px;
        }
        .div1 {
            background-color: red;
        }
        .div2 {
            background-color: blue;
            float: left;
        }
        .div3 {
            background-color: yellow;
        }
        .parent{
             overflow: hidden;
            //width:98%;
        }
</style>
    
<div class="parent">
    <div class="div1"></div>
    <div class="div2"></div>
</div>
<div class="div3"></div>