css中position屬性詳解
在CSS中關於定位的內容是:position:static ,relative , absolute , fixed ,sticky
• static 默認值,自動定位,文檔流中的位置,自動定位就是元素在頁面普通文檔流中由HTML自動定位。
• absolute 絕對定位,絕對定位脫離文檔流,依據最近的已經定位(絕對、相對或固定定位)的父元素,通過 top,bottom,left,right 定位。當父級 position 爲 static 時,absolute元素將依據body根元素(瀏覽器窗口)進行定 位,可以通過z-index進行層次分級。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position/position</title>
<style type="text/css">
div{
height: 100px;
width:200px;
background-color: blue;
opacity: 0.5;
}
.ab{
position: absolute;
left: 50px;
top: 50px;
background-color: pink;
}
</style>
</head>
<body>
<div>1</div>
<div class="ab" >2</div>
</body>
</html>
• relative 相對定位,相對定位不脫離文檔流,參考其在原來文檔流中的位置,通過 top,bottom,left,right 定位,並 且可以通過z-index進行層次分級。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position/position</title>
<style type="text/css">
div{
height: 100px;
width:200px;
background-color: blue;
opacity: 0.5;
}
.ab{
position: relative;
left: 50px;
top: 50px;
background-color: pink;
}
</style>
</head>
<body>
<div>1</div>
<div class="ab" >2</div>
<div>3</div>
</body>
</html>
• fixed 固定定位,固定定位與父元素無關(無論父元素是否定位),直接根據瀏覽器窗口定位,且不隨滾動條拖動 頁面而滾動,可通過z-index進行層次分級。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position/position</title>
<style type="text/css">
div{
height: 100px;
width:200px;
background-color: blue;
opacity: 0.5;
}
.ab{
position: fixed;
left: 50px;
top: 50px;
background-color: pink;
}
</style>
</head>
<body>
<div>1</div>
<div class="ab" >2</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
</body>
</html>
• **sticky:**英文字面意思是粘,粘貼,所以可以把它稱之爲粘性定位。
position: sticky; 基於用戶的滾動位置來定位。
粘性定位的元素是依賴於用戶的滾動,在 position:relative 與 position:fixed 定位之間切換。
它的行爲就像 position:relative; 而當頁面滾動超出目標區域時,它的表現就像 position:fixed;,它會固定在目標位置。
元素定位表現爲在跨越特定閾值前爲相對定位,之後爲固定定位。
這個特定閾值指的是 top, right, bottom 或 left 之一,換言之,指定 top, right, bottom 或 left 四個閾值其中之一,纔可使粘性定位生效。否則其行爲與相對定位相同。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position/position</title>
<style type="text/css">
div{
height: 90px;
width: 200px;
background-color: pink;
opacity: 0.5;
}
.ab{
height: 90px;
width: 200px;
background-color: blue;
opacity: 0.5;
position: sticky;
top:0;
margin-top:20px;
}
</style>
</head>
<body>
<div>1</div>
<div class="ab">2</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
</body>
</html>