解決內部容器float浮動後不能撐開外部容器及CSS偽類:after的使用

來源:互聯網
上載者:User

解決內部容器float浮動後不能撐開外部容器,外部容器塌陷問題

方法一:

直接在內部添加一個空的容器<div style="clear:both;"></div>可以撐開外部容器。

方法二:

.clearfix:after {
    content:".";
    display:block;
    height:0;
    clear:both;
    visibility:hidden;
}
*html .clearfix {
    height:1%;
}
*+html .clearfix {
    height:1%;
}

有點意思,content:"."會在指定了.clearfix樣式的容器內追加一個字元,一個英文句號。可想而知,如果樣式是.clearfix:before{content:"我想加的內容";……},那麼會在前面插入一個字串“我想加的內容”。

IE8+ 和其他較新瀏覽器都支援:after和content,我們可以使用:after+content方法清除浮動造成的塌陷。但IE6和IE7不支 持:after偽類,*、*+是分別解決IE6和IE7下的浮動塌陷問題,當然你也可以使用IE私人的zoom屬性,讓div遠離浮動塌陷問題。代碼如 下:

.clearfix {
    *zoom:1;
}
.clearfix:after {
    display:block;
    content:".";
    height:0;
    clear:both;
    overflow:hidden;
    visibility:hidden;
}

需要說明的是:overflow:hidden:的作用只是隱藏元素溢出,visibility:hidden;的作用是隱藏元素但仍然影響布局,元素佔有的空間大小還在哦。

另 外,:after偽類+content 可以讓大小不固定的圖片垂直置中,與清除浮動影響類似,IE6/7不支援:after偽類,我們可以用另外的方法讓圖片垂直置中,例如font-size 方法,設一個比較大點的字型大小,IE6/7就可以實現圖片垂直對齊了,至於其他瀏覽器,就用:after偽類+content內容產生一個 vertical-align:middle屬性的元素就可以了。

CSS:
.pic_box {
    width:300px;
    height:300px;
    background:#999;
    font-size:0;
    *font-size:200px;
    text-align:center;
}
.pic_box img {
    vertical-align:middle;
}
.pic_box:after {
    display:inline-block;
    width:0;
    height:100%;
    content:"center";
    vertical-align:middle;
    overflow:hidden;
}
HTML:
<div class="pic_box">
    <img src="http://blog.163.com/zzjjll_cool/blog/example.jpg">
</div>

目前圖片置中的測試結果是所有瀏覽器都垂直置中,但Chrome瀏覽器的水平置中貌似左邊位移了點,這是因為Chrome瀏覽器font-size:0,不能消除空格產生的水平距離的原因。這或許是唯一點瑕疵吧。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.