1. 程式人生 > >深入理解系列之 float

深入理解系列之 float

子元素 out oat 理解 oom 20px 布局 空格 ble

float的設計初衷:

僅僅是為了實現文字環繞效果

float的感性認知:

  1. 包裹性:
    1. 收縮:元素應用了float後,寬度收縮,緊緊地包裹住內容(即元素的寬度收縮到元素內的內容的寬度大小
    2. 堅挺:原來沒有高度,但元素應用了float後,元素的高度突然擴展到內容的高度大小
    3. 隔絕:元素應用了float後,盒子裏面的內容發生了任何事情,都與盒子外的內容無關(BFC)
  2. 破壞性:
    1. 子元素應用了float後,父容器塌陷:父容器的高度變為0

tips: 具有包裹性(BFC特性)的其他屬性:
display: inline-block/table-cell
position: absolute/fixed/sticky
overflow: hidden/scroll
具有破壞性的其他屬性:
display: none
position: absolute/fixed/sticky

清除float對其他元素所帶來的影響:

  1. float元素底部插入一個帶有 clear: both; 屬性的元素
    1. 底部放置一個HTML block水平元素 -
    2. CSS after(IE8+)偽元素底部生成 - .clearfix:after{ clear: both; }
  2. 父元素BFC化(IE8+)或 haslayout(IE6/7)

BFC/haslayout的通常聲明

  1. float: left/right
  2. position: absolute/fixed
  3. overflow: hidden/scroll(IE7+)
  4. display: inline-block/table-cell(IE8+)
  5. width/height/zoom: 1/...(IE6/7)

綜上,IE8以上瀏覽器使用:
```css
.clearfix:after {
content: ‘‘;
display: block;
height: 0;
overflow: hidden;
clear: both;
}

.clearfix {
*zoom: 1;
}

css
/更好的方法/
.clearfix:after {
content: ‘‘;
display: block;
height: 0;
overflow: hidden;
clear: both;
}

.clearfix {
*zoom: 1;
}
```

切記,.clearfix 只需應用在浮動元素的父級元素上 浮動的特性:

  1. 元素block塊狀化(磚頭化)
  2. 破壞性造成的緊密排列特性(去空格化)

智能化自適應布局

<div class="container"><a href="#" class="left"><img src="url"/></a>
    <div class="right">很多其他內容</div>
</div>
  .container {
        width: 600px;
        margin: auto;
    }

    .left {
        float: left;
        margin-right: 20px;
    }

    .right {
        display: table-cell;
        *display: inline-block;
        width: 2000px;
        *width: auto;
    }

深入理解系列之 float