首页 > 使用:after伪元素清除浮动

使用:after伪元素清除浮动

在练习元素清除浮动的时候,遇到了几个问题:
1.内联元素是否不能用来清除浮动?
2.使用:after清除浮动时,有哪些需要注意的(调试过程中并没有使用此方法成功清除浮动)?
下面的HTML代码中,想使用:after清除浮动,但是并没有生效,定位不到什么问题:

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

/*在此定义相应的类选择器,并根据要求设置相关CSS属性*/
/** {
    margin: 0px;
    padding: 0px;
}
*/
.mainBox {
    width: 960px;
    /*height: 300px;*/
    background-color:#cff;
    /*overflow: hidden;*/
    /*zoom: 1;*/
}
.mainBox:after{
    display: "block";
    clear:both;
    height:0;
    content: "";
    visibility: hidden;
    overflow:hidden;
}
.leftBox {
    background-color:#C9F;
    width:740px;
    height: 300px;
    float: left;
}
.rightBox {
    background-color:#FCF;
    width:210px;
    height: 300px;
    margin-left:10px;
    float: right;
}

</style>
</head>

<body>
    <div class="mainBox">
        <div class="leftBox">
        </div>
        <div class="rightBox">
        </div>
        <!-- <div style="clear: both"></div> -->
        <!-- <span style="clear: both"></span> -->
    </div>
</body>
</html>

你的after样式中display属性写错了,没有引号的


1.clear属性只适用于块级元素
2.after伪元素加在mainBox容器上,mainBox容器本省并没没有浮动,对其子元素是不会有影响

现在代码看到的效果是mainBox有宽度,没有高度,是因为按正常的块级元素的在高度为height不显式设置(height:auto)的情况下,高度为其下所有最高块级元素的上外边界(最高行内框的上边界)和最低元素下外边界(最低行内框的下外边界)的距离或;但是设置了浮动的属性的元素将从正常流布局渲染中脱离,不参与父容器高度的计算。
想要得到正常的容器高度,就需要清楚浮动,就需要用BFC,就需要使得元素形成一个新的BFC,设置overflow:hidden就能形成个BFC,就可以解决高度问题,一个BFC内浮动元素的参与容器高度的计算

.mainBox {
    width: 960px;
    /*height: 300px;*/
    background-color:#cff;
    overflow: hidden;
    /*zoom: 1;*/
}

在div.mainBox上添加after伪元素也可以达到同样的目的

.mainBox:after{
            display:block;
            clear:both;
            height:0;
            content: "";
            visibility: hidden;
            overflow:hidden;
}

其效果相当于:
不为div.mainBox添加after伪元素,直接在div.mainBox添加一个宽高为0的clear:both的div元素

<div class="mainBox">
    <div class="leftBox"></div>
    <div class="rightBox"></div>
    <div style="clear: both;"></div>
     <!--<span style="clear: both;width:100px;height:100px"></span>-->
</div>

参考我之前的一个问题看看
https://.com/q/1010000004345737

【热门文章】
【热门文章】