[CSS]position:static|relative|absolute|fixed
1.相对定位|relative
相对于元素在文档流中的初始位置。
相对定位的元素占据文档流,属于普通流定位模型的一部分,对一个元素进行相对定位,这个元素相对于它的起点(即在文档中的位置)进行移动top/left/right/bottom。使用相对定位时,无论是否进行移动,元素仍占据原来空间,移动元素会导致覆盖其他框。
2.绝对定位|absolute
相对于最近的已定位的祖先元素。
绝对定位使元素与文档流无关,不占据文档空间。普通流中的元素会表现的好像绝对定位的元素并不存在一样。绝对定位的元素的位置相对于最近的已定位的祖先元素。若元素没有已定位的祖先元素,那么元素的位置相对于最初的包含块,依据浏览器不同,最初包含块可能为canvas或者html元素。
何谓 已定位的祖先元素(包含块) ?
Take a look at what the CSS 2.1 specification has to say about containing blocks:
If the element has ‘position: absolute’, the containing block is established by the nearest ancestor with a ‘position’ of ‘absolute’, ‘relative’ or ‘fixed’ … If there is no such ancestor, the containing block is the initial containing block.
祖先元素(包含块)是指具有position:absolute|relative|fixed的祖先元素
3.固顶定位|fixed
属于绝对定位的一个子类,包含块是viewport。
理论永远是枯燥的,以下上我学习时写得例子。就像我说的,这是我学习时写的例子,所以,样子可以说是奇丑无比,以至于我都不愿意把它丑陋的样子展示出来,所以,以下只给除html以及css的源代码。
default.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="zh-CN" xml:lang="zh-CN" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Author" content="" />
<link href="style.css" rel="stylesheet" type="text/css" media="screen" title="position" />
<title>Position example</title>
</head>
<body>
<div id="content">
<div id="myBox0">myBox0</div>
<div id="myBox1">myBox1
<div id="myBox6">myBox6</div>
</div>
<div id="myBox2">myBox2
<div id="myBox5">myBox5</div>
</div>
<div id="myBox3">myBox3</div>
<div id="myBox4">myBox4</div>
<div id="myBox7">myBox7</div>
</div>
</body>
</html>
style.css
*{
margin: 0;
padding: 0;
}
body{
text-align: center;
}
#content{
width: 800px;
height: 100%;
margin: 0 auto;
background: Fuchsia;
text-align: left;
}
#myBox0{
width: 200px;
height: 300px;
background: red;
}
#myBox1{
position: relative;
left: 20px;
top: 20px;
width: 100px;
height: 200px;
background: Aqua;
}
#myBox2{
position: absolute;
left: 20px;
top: 20px;
width: 200px;
height: 300px;
background: yellow;
}
#myBox3{
position: static;
width: 300px;
height: 400px;
background: orange;
}
#myBox4{
position: fixed;
top: 100px;
right: 300px;
width: 100px;
height: 50px;
background: #fff;
}
#myBox5{
position: absolute;
left: 20px;
top: 80px;
width: 120px;
height: 30px;
background: blue;
}
#myBox6{
position: absolute;
left: 20px;
top: 80px;
width: 120px;
height: 30px;
background: green;
}
#myBox7{
position: absolute;
left: 120px;
top: 180px;
width: 50px;
height: 50px;
background: black;
}
- May
- 12
- 2007
- 糖伴西红柿
- Z-Blog
- Comments (0)
- Tags: CSS —












