一、position的概念
作为布局必不可缺少的元素之一,深究其属性以及一些注意点是非常必要的。
定义:规定元素的定位类型。
position属性:
| 属性 | 描述 | 常用性 |
|---|---|---|
| absolute | 生成绝对定位的元素,相对于static定位以外的第一个父元素进行定位。 | ★★ |
| relative | 生成相对定位的元素,相对于其在文档流正常位置进行定位。 | ★★ |
| fixed | 生成绝对定位的元素,相对于浏览器窗口进行定位。 | ★☆ |
| static | 默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明) | ☆☆ |
从表格中可以了解到position的主要概念,有几点需要注意:
二、position属性的一些注意点
1. absolute的定位问题
absolute所定位的位置是最近带有position属性并且属性值不为static的父级元素。子元素默认定位在父元素的左上角位置。
如果子元素仅仅设置了position:absolute,而未设置left、top之类的元素。和对应的padding无关。
举个例子:如果子元素设置了bottom:0;如果父元素存在padding:20px;那么padding-bottom:20px;会失效,但是padding-left:20px;依然奏效。比如:
//css div{ width:200px; height:200px; } .fatherDiv{ background-color:#12B7F5; position:relative; padding:20px; margin-top:20px; } .childDiv{ width:100px; height:100px; background-color:#F9b041; position:absolute; bottom:0px; } //html <div class="fatherDiv"> <div class="childDiv"></div> </div>
当然如果你既设置了left、又设置了bottom.那么父元素的padding的任何设置是对子元素产生不了任何影响
这里需要注意,margin无论什么值都也都会影响到子元素,因为它是直接影响父级。
2. relative的定位问题
以下例子都以下面为基础样式
//css div{ width:200px; height:200px; } .brotherDiv{ background-color:#12B7F5; } .brotherDiv1{ background-color:#F9b041; } //html <div class="brotherDiv"></div> <div class="brotherDiv1"></div>i. 两个div为块级(block)元素
两者的left、top....都不会相互影响.因为即使元素位置改变了,但是它在文档流占用的空间不变,所以并不会影响到布局。
.brotherDiv{ position:relative; top:40px; } .brotherDiv1{ position: relative; }
另外还
