關于position:absolute
- 絕對定位元素相對于最近的非 static 祖先元素定位。
- 當這樣的祖先元素不存在時,則相對于ICB(inital container block, 初始包含塊)。-----------------MDN官網
ICB(inital container block, 初始包含塊)
關于包含塊
- 什麼是包含塊:大多數情況下,包含塊就是這個元素最近的祖先塊元素的内容區,但也不是總是這樣。
- 包含塊的确定:确定一個元素的包含塊的過程完全依賴于這個元素的 position 屬性。(具體确定方法可檢視MDN官方文檔)
- 初始包含塊:同視口大小或分頁媒體一樣大小的矩形
注意: 根元素(<html>)所在的包含塊是一個被稱為初始包含塊的矩形。他的尺寸是視口 viewport (for continuous media) 或分頁媒體 page media (for paged media).
position的包含塊
- 對于設定有position屬性的元素,若position:relative或者static,那麼包含塊為最近的塊級祖先元素的内容區域
- 對于設定有position屬性的元素,若position:absolute那麼包含塊由離此元素最近的設定有position屬性(但非static)的祖先元素
body和html
-
<html>:根元素
HTML <html> 元素 表示一個HTML文檔的根(頂級元素),是以它也被稱為根元素。所有其他元素必須是此元素的後代。
-
<body> :文檔主體元素(必須是html的直接子元素)
HTML <body> 元素表示文檔的内容。document.body 屬性提供了可以輕松通路文檔的 body 元素的腳本。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>給body設定滾動條</title>
<style>
*{
margin: 0;
padding: 0;
}
html{
margin: 30px;
height: 80%;
border: 1px solid;
overflow: hidden; /* 禁用浏覽器滾動條 */
background-color: chartreuse;
}
body{
margin: 30px;
height: 80%;
border: 1px solid deeppink;
overflow: auto; /* 給body添加滾動條 */
background-color: chocolate;
}
</style>
</head>
<body>
<div style="height: 3000px;"></div>
</body>
</html>
用absolute實作fixed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html{
overflow: hidden; /* 禁用浏覽器滾動條 */
height: 100%; /* 浏覽器視口高度 */
}
body{
overflow: auto; /* 給body設定滾動條 */
height: 100%; /* 浏覽器視口高度 */
}
#box1{
width: 200px;
height: 200px;
background-color: burlywood;
position: absolute; /* absolate 此時相當于fixed*/
left: 100px;
top: 100px;
}
</style>
</head>
<body>
<div id="box1"></div>
<div style="height:1000px">可滾動的div</div>
</body>
</html>
而
id
為
box1
的
div
由于沒有開啟定位的祖先元素,會始終依據初始包含塊來偏移,又因為
html
的overflow為hidden,
document
沒有滾動條,初始包含塊的位置不會變化,也不受
body
的滾動條影響,是以依據其定位的div不會随滾動條而滾動,這樣就實作了
fixed
的效果。
————————————————
版權聲明:本文為CSDN部落客「塵埃丶落定」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。
原文連結:https://blog.csdn.net/longyin0528/article/details/80777809
滾動條
- 當
,body
元素同時出現overflow屬性時,滾動條出現在html
上(body
的overflow值設定為auto,body
元素的overflow值任意)html
- 如果,
,body
元素中隻有一個有overflow屬性,那麼滾動條出現在html
的上一級,即視口(初始包含塊)html
總上所述
- 如果position:absolute不存在非 static 祖先元素,則相對于初始包含塊。初始包含塊是同視口大小或分頁媒體一樣大小的矩形。<html>就存在于初始包含塊中,而<body>必須是<html>的直接子元素。
- 由于不存在非 static 祖先元素,則相對于初始包含塊,則可聯想到由absolute實作fixed的功能:使設定absolute的元素也可以相對于視口(初始包含塊)固定定位。
- 但同時涉及到
和<html>
滾動條的知識,須要禁用<body>
上的滾動條,給html
添加滾動條。這樣使得初始包含塊不再變化,body
的高度為視口高度,滾動的則是内部的body
。進而實作了div
的效果。fixed
如有不足:請指正:D