# CSS position屬性
[TOC]
CSS 有三種基本的定位機制:普通流、浮動和絕對定位。
我們已經學習了普通流和浮動的相關內容,本節我們介紹定位相關內容。
position屬性設置元素定位類型,可以通過top,bottom,right,left屬性,控制元素的定位位置。
position屬性值有static,relative,absolute,fixed四個值。
## static靜態定位
HTML元素的默認值,即沒有定位,元素出現在正常的流中。
靜態定位的元素不會受到top,bottom,right,left屬性的影響。
## fixed固定定位
* 脫離標準流,在頁面中不占位置 。
* 不管頁面有多大,永遠相對于瀏覽器的邊框來定位 。
```css
*{
margin: 0;
padding: 0;
}
.c1{
width: 100px;
height: 100px;
background-color: brown;
}
.c2{
width: 100px;
height: 100px;
background-color: blue;
}
.c3{
width: 100px;
height: 100px;
background-color: black;
position: fixed;/*固定定位,不占位置,永遠相對于瀏覽器來定位,不管窗口上下拉動,都不會消失(如廣告位)*/
left:20px;
top:20px;
}
```
```html
<body>
<div class="c1"></div>
<div class="c2"></div>
<div class="c3"></div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>...
</body>
```
## relative 相對定位
* 不脫離標準流,在頁面中占位置 。
* 相對于自己原來的位置來進行定位 。
```css
*{
margin: 0;
padding: 0;
}
.c1{
width: 100px;
height: 100px;
background-color: brown;
}
.c2{
width: 100px;
height: 100px;
background-color: blue;
position: relative;/*相對定位,占位置,相對于自己原來的位置定位*/
left: 20px;
top:20px;
}
.c3{
width: 100px;
height: 100px;
background-color: black;
}
```
```html
<body>
<div class="c1"></div>
<div class="c2"></div>
<div class="c3"></div>
</body>
```
## absolute絕對定位
* 脫離標準流,在頁面中不占位置(浮起來)。
* 如果沒有父元素,則相對于body定位;如果有父元素,但父元素沒有定位,那么還是相對于body定位;如果父元素有定位,那么相對于父元素來定位。
```css
*{
margin: 0;
padding: 0;
}
.c1{
width: 100px;
height: 100px;
background-color: brown;
position: absolute;/*絕對定位,不占位置,無父級定位則相對于body來定位*/
left:20px;
top:20px;
}
.c2{
width: 100px;
height: 100px;
background-color: blue;
}
.c3{
width: 100px;
height: 100px;
background-color: black;
}
```
```html
<div class="c1"></div>
<div class="c2"></div>
<div class="c3"></div>
```
## 定位元素的重疊
* `z-index`屬性控制定位元素的重疊順序,屬性值是z軸上的值。
* `z-index`的值是設置一個定位元素沿Z軸的位置,其值越大,離用戶越近,所以若兩個定位元素,`z-index`值越大的將會覆蓋值越小的定位元素。
默認值是0,可以是正負數。
下面首先不設置z-index。
~~~html
<head>
<style>
img.a2
{
position:relative;
left:0px;
top:-60px;
z-index:-1;
}
.a1 {
position:relative;
z-index:-1
}
.yu {
position:relative;
left:0px;
top:30px;
z-index:auto;
background:red
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<img class="a2" src="w3css.gif" width="100" height="140" />
<p>因為圖像元素設置了 z-index 屬性值為 -1, 所以它會顯示在文字之后。</p>
<div class="yu">
<p>定位</p>
<img class="a1" src="w3css.gif" width="100" height="140" />
<div>
</body>
~~~
>[warning]一般而言,`z-index`的值只能與同級元素或其他自由元素比較,如果想要使父元素覆蓋子元素,可以設置父元素的z-index屬性值為auto,子元素的z-index值為負數