1、屬性分析
- display屬性:規定元素生成框的類型。較爲常見的有none-缺省值(用於隱藏元素,元素會消失於視界和文檔流中),block-塊級元素,inline-block-行內塊級元素,list-item列表樣式塊級元素等。
- position屬性:規定元素的定位類型,常用於佈局。static-默認值,元素出現在正常文檔流中(此時不受top、left、right、bottom、z-index等屬性影響);absolute-絕對定位,脫離文檔流,相對於它第一個非static父元素進行定;fixed-固定定位,相對於瀏覽器窗口進行定位;relative生成相對定位的元素,相對於其正常文檔流中的位置進行定位。
- float屬性:定義一個元素浮動方向,最初用於圖像使文本環繞,現在是一種佈局方式。不論浮動元素本身是何種框類型,浮動後會生成一個塊級框。
2、相互作用關係
display轉換對應表:
設定值 | 轉換後 |
---|---|
inline-table | table |
inline, inline-block,run-in,table-row-group,table-column,table-column-groupt,able-header-group,table-footer-group,table-row,table-cell,table-caption | block |
其他 | 保持設定值 |
下面分情況討論:
1.display值爲none
當元素display值爲none時,元素不產生框,float和position都不起作用。
2.position是absolute或fixed
當元素display值不爲none,而position是absolute或者fixed時,此時float不起作用,計算值也爲none(原文中有計算方法,這裏略去),display值會按上表設置。元素框的位置由top、left、right、bottom值和其父元素決定。
3.float值不爲none
當元素有了浮動屬性(float不爲none,是left或right)後,該框浮動且display值會按上表轉換。例如,span是行內元素,設置浮動後會變爲塊級元素。
4.元素爲根元素
如果元素是根元素,設置的display也會按上表進行轉換。否則,元素的display值爲指定值或默認值。
3、案例分析
利用 clear 屬性 和 替身法 消除 浮動
注:clear屬性:
值 | 描述 |
---|---|
left | 在左側不允許浮動元素。 |
right | 在右側不允許浮動元素。 |
both | 在左右兩側均不允許浮動元素。 |
none | 默認值。允許浮動元素出現在兩側。 |
inherit | 規定應該從父元素繼承 clear 屬性的值。 |
案例代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>position和float相互覆蓋</title>
<style type="text/css">
.first{
width: 200px;
height: 200px;
}
.div1{
background: red;
width: 100px;
height: 100px;
float: left;
}
.div2{
background: blue;
width: 100px;
height: 100px;
float: left;
}
.clean {
/*clear用於清除浮動*/
clear: left;
}
.second{
width: 200px;
height: 200px;
}
.div3{
background: red;
width: 100px;
height: 100px;
position: absolute;
}
.div4{
background:green;
width: 100px;
height: 100px;
}
.div5{
background: black;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="first">
<div class="div1"></div>
<div class="clean"></div>
<div class="div2"></div>
</div>
<div class="second">
<div class="div3"></div>
<!--替身法消除浮動-->
<div class="div4"></div>
<div class="div5"></div>
</div>
</body>
</html>