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>