---
title: "CSS中的Position属性 (转)"
author: "moonlight2010"
date: "2013-04-26T16:12:16Z"
tags: ["CSS", "position", "属性"]
categories: ["Web前端"]
slug: "css-position"
draft: false
lastmod: "2013-04-26T16:12:16Z"
id: 1855283
url: "https://moonlight2010.iteye.com/blog/1855283"
---

CSS中的Position属性 也许你看到这个标题觉得很简单，确实这是一篇关于CSS中Position属性基础知识的文章，但是关于Position的一些细节也许你不了解。 1、简介 position有五个属性： static | relative | absolute | fixed | inherit static 和 inherit : 没什么值得介绍的。 relative : 相对于元素自身的定位。 absolute ：相对于包含块的定位。 fixed : 相对于窗口的定位。 2、包含块 包含块就是 top | right | bottom | left 参考的元素。 absolute的包含块指的是：该元素最近的具有定位设置的父元素，即最近的position属性值不为static的祖先元素举个例子：

span

对于span元素来讲，它的包含块是#outer，而不是#inner,因为#outer设置了 position:absolute。值得注意的是，只要#outer设置了 absolute | relative | fixed span元素的“定位父元素”就是#outer，如果outer没有设置三种属性的其中之一，则span的包含块就是html元素。 relative的包含块指的是：元素自身。 3、top | right | bottom | left 的细节。 也许你会想当然的认为这些值有什么细节可言，那你就错了。在此以left为例： left值 = “定位父元素”border内边 到 该元素margin外边的举例 ，简单的记忆就是“border内,margin外”。 right | bottom | left 也是这种道理 4、z-index 关于z-index的细节，这里就不说了，因为觉得自己表达不清，而且《CSS权威指南》相应章节里对z-index讲的非常清楚(特别是叠放上下文的相关知识)，这些知识是非常有用的。 如果你能看懂下面这个层叠顺序，则证明你对z-index的学习已经非常成熟了。要注意其中#one1 元素 #two元素的层叠顺序。 例子：http://www.kangchangan.cn/cnblog/zIndexStackingContext.html 5、postion 与文档流 只要元素设置了 postion : absolute | relative | fixed ， 该元素就会脱离文档流。 但是relative元素是个特例，因为该元素对然脱离了文档流，但是它原本所占的空间仍然占据文档流。 例如： Code relative

rain-man rain-man rain-man rain-man rain-man  
rain-man rain-man cnblog rain-man rain-man  
rain-man rain-man rain-man rain-man  
rain-man rain-man rain-man rain-man  
rain-man rain-man rain-man rain-man

6、positon 与 display 元素分为内联元素和区块元素两类（当然也有其它的），在内联元素中有个非常重要的常识，即内两元素是不可以设置区块元素所具有的样式，例如:width | height。 relative : 原来是什么类型的依旧是什么类型。 absolute | fixed ： 元素就被重置为了区块元素，例如：打算为span元素指定大小，并绝对定位 span这是完全正确的， span，这里的display:block就是多余的了。 7、position 与 float 一个元素若设置了 position:absolute | fixed; 则该元素就不能设置float。这是一个常识性的知识点，因为这是两个不同的流，一个是浮动流，另一个是“定位流(这是自己起的名字，呵呵)”。 但是 relative 却可以。因为它原本所占的空间仍然占据文档流。 8、Bug Bug1: 参考网页: http://therealcrisp.xs4all.nl/meuk/IE-zindexbug.html，哎这个就是IE的bug了，解决办法就是为#container设置 z-index:11 || 大于10的整数。 Bug2： bug页面：http://www.kangchangan.cn/cnblog/floatPosition.html 解决页面：http://www.kangchangan.cn/cnblog/floatPosition2.html 相关解释已经在解决页面了。