absolute、relative、fixed、static 這四種定位方式,光看文字很抽象,實際跑一次卻會發現彼此有微妙的父子關係。這個範例把四種定位全部放進同一個頁面,透過捲動與縮放視窗就能觀察差異。
效果預覽:https:///keleyi/phtml/divcss/3.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>div css position 屬性 absolute relative fixed static 定位樣式表</title>
<meta name="description" content="div css 樣式表 position 屬性有 absolute、relative、fixed、static,分別是絕對定位、相對定位、固定定位、靜態定位等 4 種定位樣式表。" />
<link rel="stylesheet" type="text/css" href="https:///keleyi/phtml/divcss/3/style.css" />
</head>
<body>
<div id="iAmFixed_keleyi_com">
I am fixed (scroll the page)
<pre>background-color:#F6E4F5;
border:1px solid white;
padding:15px;
right:95px;
width:300px;
z-index:10;
<b>position:fixed;
bottom:15px;</b>
</pre>
<div id="iAmAbsoluteInsideFixed_keleyi_com"> I am absolute inside fixed
<pre>background-color:#DCF4F9;
border:1px solid white;
padding:15px;
<b>position:absolute;
right:-50px;
top:-90px;</b></pre>
</div>
</div>
<div id="iAmAbsolute_keleyi_com">I am a lonely absolute
<pre>background-color:#DCF9E1;
border:1px solid white;
padding:15px;
width:150px;
<b>position:absolute;
top:0;
left:0;</b></pre>
</div>
<div id="iAmRelative_keleyi_com">I am relative (resize window)
<pre>background-color:#F8F7C3;
border:1px solid white;
width:200px;
padding:20px;
<b>position:relative;
left:400px;</b></pre>
<div id="iAmAbsoluteInsideRelative_keleyi_com">I am absolute inside relative
<pre>background-color:#F8D9C3;
border:1px solid white;
padding:20px;
<b>position:absolute;
left:-180px;
bottom:-140px;</b></pre>
</div>
</div>
</body>
</html>
/* https:// */
*{
/* Page reset */
margin:0;
padding:0;
}
body{
/* Body Styles */
font-size:12px;
color:#666;
background-color:#f8f8f8;
font-family:Arial, Helvetica, sans-serif;
height:3000px
}
#iAmFixed_keleyi_com{
background-color:#F6E4F5;
border:1px solid white;
bottom:15px;
padding:15px;
position:fixed;
right:95px;
width:300px;
z-index:10;
}
#iAmAbsoluteInsideFixed_keleyi_com{
background-color:#DCF4F9;
border:1px solid white;
padding:15px;
position:absolute;
right:-50px;
top:-90px;
}
#iAmAbsolute_keleyi_com{
background-color:#DCF9E1;
border:1px solid white;
left:0;
padding:15px;
position:absolute;
top:0;
width:150px;
}
#iAmRelative_keleyi_com{
background-color:#F8F7C3;
border:1px solid white;
left:400px;
padding:20px;
position:relative;
width:200px;
}
#iAmAbsoluteInsideRelative_keleyi_com{
background-color:#F8D9C3;
border:1px solid white;
bottom:-140px;
left:-180px;
padding:20px;
position:absolute;
}
pre{
background-color:rgba(255, 255, 255, 0.35);
color:#888888;
font-family:Arial,Helvetica,sans-serif;
font-size:10px;
margin-top:10px;
padding:10px;
}
pre b{
color:black;
font-weight:normal;
}
一句話總結:absolute 是「找最近的已定位祖先當錨點」,fixed 是「以視窗為錨點」,relative 是「以自己原本的位置為錨點並保留佔位」。把這個範例跑一遍,比讀十遍文件都有效。