css定位之position详细解读

来源:互联网 发布:53端口 转发 编辑:程序博客网 时间:2024/05/22 11:47

position这个属性使用非常频繁,扪心自问,似乎又不是很明白,特别是absolute,有种爱在心口难开的感觉,难受,今天就一探究竟

static

默认值。没有定位,元素出现在常规流中( 忽略 top, bottom, left, right 或者 z-index 声明)。

PS:常规流,是对 “normal flow” 的直译。
之称之为常规流,是因为这是相对于浮动和绝对定位的一个概念,浮动和绝对定位元素都脱离了当前的常规流。
在 CSS2.1中,常规流包括块框( block boxes )的块格式化( block formatting ), 行内框( inline boxes )的行内格式化( inline formatting ),块框或行内框的相对定位,以及插入框的定位。

inherit

规定应该从父元素继承 position 属性的值。( z-index 声明有用
这个大家都应该理解,不多说

fixed

生成绝对定位的元素,相对于浏览器窗口进行定位。( z-index 声明有用
元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。
例如:常见的back-to-top
这里写图片描述

大boss(absolute)

生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。
如果没有除static以外的定位,则相对body定位
元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。( z-index 声明有用
例子:
结构:

    <p>hei,今天写博客了吗</p>    <div class="container">        <div class="item">我是item</div>    </div>

样式

    * {        margin: 0;        padding: 0;    }      p {        font-size: 30px;        background: yellow;        border: 10px solid #ccc;    }      .container {        background: red;        border: 10px dashed red;    }     .container .item {        position: absolute;        left: 0;        top: 0;        background: blue;        border: 10px dashed blue;    }

结果:(除static外没有其它定位,相对body定位)左上角为body起始点。
右边为添加absolute后的结果

这里写图片描述=>这里写图片描述

到这里,都没有什么难理解的,但是,当我们只设置absolute,不设置top,left,看看发生生么?
新样式:

    * {        margin: 0;        padding: 0;    }      p {        font-size: 30px;        background: yellow;        border: 10px solid #ccc;    }      .container {        background: red;        border: 10px dashed red;    }     .container .item {        position: absolute;        /* left: 0;         top: 0; */ /*不设置top,left*/        background: blue;        border: 10px dashed blue;    }

结果:是脱离了标准文档流
这里写图片描述

但是很意外,它居然相对红色部分进行定位,为什么呢?

如果绝对定位元素没有申明置入值(left\right\top\bottom),只申明了position:absolute,那么其自身定位以及margin的参照物即为其最近的块级、单元格(table cell)或者行内块(inline-block)祖先元素的 内容框。

relative

生成相对定位的元素,相对于常规流(normal flow)进行定位。
z-index 声明有用

参考

  • http://www.w3school.com.cn/cssref/pr_class_position.asp

  • http://www.zhangxinxu.com/wordpress/2010/01/absolute%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D%E7%9A%84%E9%9D%9E%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D%E7%94%A8%E6%B3%95/
    ps:欢迎交流

0 0