清楚浮动

Author Avatar
Ninefire 6月 07, 2018
  • 在其它设备中阅读本文章

六种清楚浮动的方法

  • 给父元素添加高度(扩展性不好)
    例:
<!-- CSS -->
<style type="text/css">
    .wrap {
        background: #bfa;
        /* 指定高度为子元素的高度 */
        height: 100px;
    }

    .wrap .inner {
        float: left;
        width: 100px;
        height: 100px;
        background: orange;
    }
<style/>

<!-- HTML -->
<body>
    <div class="wrap">
        <div class="inner"><div/>
    <div/>
<body/>
  • 给父元素添加浮动(页面中所有元素都加浮动,margin左右自动失效(floats bad!))
    例:
<!-- CSS -->
<style type="text/css">
    .wrap {
        background: #bfa;
        float: left;
    }

    .wrap .inner {
        float: left;
        width: 100px;
        height: 100px;
        background: orange;
    }
<style/>

<!-- HTML -->
<body>
    <div class="wrap">
        <div class="inner"><div/>
    <div/>
<body/>
  • 空标签清楚浮动(IE6最小高度19px(处理后IE6下还有2px偏差))
    例:
<!-- CSS -->
<style type="text/css">
    .wrap {
        background: #bfa;
    }

    .wrap .inner {
        float: left;
        width: 100px;
        height: 100px;
        background: orange;
    }
<style/>

<!-- HTML -->
<body>
    <div class="wrap">
        <div class="inner"><div/>
        <div style="clear: both;"><div/>
    <div/>
<body/>
  • <br/>清楚浮动(不符合“结构、样式、行为”三者分离的要求)
    例:
<!-- CSS -->
<style type="text/css">
    .wrap {
        background: #bfa;
    }

    .wrap .inner {
        float: left;
        width: 100px;
        height: 100px;
        background: orange;
    }
<style/>

<!-- HTML -->
<body>
    <div class="wrap">
        <div class="inner"><div/>
        <br clear="all"/>
    <div/>
<body/>
  • overall开启BFC
    例:
<!-- CSS -->
<style type="text/css">
    .wrap {
        background: #bfa;
        overflow: hidden;
    }

    .wrap .inner {
        float: left;
        width: 100px;
        height: 100px;
        background: orange;
    }
<style/>

<!-- HTML -->
<body>
    <div class="wrap">
        <div class="inner"><div/>
    <div/>
<body/>
  • 伪元素after
    例:
<!-- CSS -->
<style type="text/css">
    .wrap {
        background: #bfa;
    }

    .wrap .inner {
        float: left;
        width: 100px;
        height: 100px;
        background: orange;
    }

    /* 兼容IE6,开启haslayout */
    .clearfix { *zoom: 1; }

    ·clearfix:after {
        content: "";
        display: block;
        clear: both;
    }
<style/>

<!-- HTML -->
<body>
    <div class="wrap clearfix">
        <div class="inner"><div/>
    <div/>
<body/>

推荐使用的clearfix写法

.clearfix {
    *zoom: 1;
}
.clearfix:before,
.clearfix:after {
    content: "";
    display: table;
    clear: both;
}

这个clearfix的写法既可以解决高度塌陷问题,也可以解决margin重叠问题。

如发现错误请联系我,谢谢你。
本文链接:http://ninefire.tk/CSS2.1/06.html