清除浮动技巧测试

声明:小白的笔记,欢迎大神指点。联系QQ:1522025433。

我们都知道当子元素浮动时,父元素的高度就会变成0,如下实例是一个在左浮动的元素,父元素有1px的蓝色边框。

css代码:

    .out {
        width: 500px;
        border: 1px solid blue;
        background-color: red;
    }
    .in {
        float:left;
        width: 200px;
        height: 200px;
        background-color: greenyellow;
    }

html代码:

<div class="out"><div class="in">我在父元素中左浮动</div></div>

效果图:

可以看出子元素浮动后父元素:父元素的高度变为了0;只剩下了边框;

怎么才能在子元素浮动的情况下,父元素还能保持与子元素的高度呢(前提条件是在父元素未定义高度,自适应子元素高度的情况下。如果定义的父元素的高度,当然浏览器还是按照实际定义的高度进行渲染)?

这是后我们就用到了:clear:both; 属性,具体是在子元素后加一个没有宽高的盒子,然后定义此盒子,两侧不许有浮动元素,即可。我们来看下面的例子:

css代码:

    .out {
        width: 500px;
        border: 1px solid blue;
        background-color: red;
    }
    .in {
        float:left;
        width: 200px;
        height: 200px;
        background-color: greenyellow;
    }
    .clear {
        clear: both;
    }

html代码:

<div class="out"><div class="in">清除浮动</div><div class="clear"></div></div>

效果图:

是不是达到我们想要的效果了!

但是这样写,html结构中就会多一个<div> 标签。怎么才能不加这个<div> 标签,又能达到这也的效果呢?哈!这时我们可以利用伪对象选择符  :after 在子元素后添加一个块状元素,具体怎么用呢,我们来看下面的示例:

css代码(.out;.in 的样式我就不写了,与上面的相同,只写为对象这一块):

    .clearfloat:after {
        display: block;/*渲染成块级元素*/
        content: '';/*无内容*/
        height:0 ;/*高度为0,宽度自适应父元素*/
        clear:both;/*清除两层浮动*/
        visibility: hidden;     /*定义此元素为 隐藏的,不可见的*/
    }

html代码:

<div class="out clearfloat"><div class="in">利用伪对象选择符清除浮动</div></div>

效果图:

这样也达到了同样的效果是不是很好呢!(我看有的大神就是这样写的,我就是跟他们学的)

最后我附上一个完整的代码(内含利用伪对象选择符清除浮动,在IE下兼容的技巧):

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>清除浮动技巧测试</title>
<style type="text/css">
    .out {
        margin-top: 10px;
        width: 500px;
        border: 1px solid blue;
        background-color: red;
    }
    .in {
        float:left;
        width: 200px;
        height: 200px;
        background-color: greenyellow;
    }
    .clear {
        clear: both;
    }
    
/*    利用伪对象选择符清除浮动*/
    
    .clearfloat {
        zoom: 1;    /*    兼容ie*/
    }
    
    .clearfloat:after {
        display: block;/*渲染成块级元素*/
        content: '';/*无内容*/
        height:0 ;/*高度为0,宽度自适应父元素*/
        clear:both;/*清除两层浮动*/
        visibility: hidden;     /*定义此元素为 隐藏的,不可见的*/
    }
</style>
</head>

<body>
<div class="out"><div class="in">清除浮动</div><div class="clear"></div></div>
<div class="out clearfloat"><div class="in">利用伪对象选择符清除浮动</div></div>
<div class="out"><div class="in">我在父元素中左浮动</div></div>
</body>
</html>

浏览器整体效果图:

结束,以后有补充再写!

原文地址:https://www.cnblogs.com/taohuaya/p/7643055.html