CSS的position属性的关键字分别是static、relative、absolute、fixed、sticky。
static
static根据文档的正常流进行定位。对top、right、bottom、left、z-index属性没有影响。这是默认值。
如图所示:
relative
relative根据文档的正常流进行定位,根据top、right、bottom、left的值相对于自身进行偏移。
效果图
HTML
<!DOCTYPE html><html> ???<head> ???????????<meta charset="utf-8"> ???????????<title>relative</title> ???????????<link href="relative.css" rel="stylesheet" type="text/css" > ???</head> ???<body> ???????????<div class="box" id="one">One</div> ???????????<div class="box" id="two">Two</div> ???????????<div class="box" id="three">Three</div> ???????????<div class="box" id="four">Four</div> ???????</body></html>
CSS
.box { ???display: inline-block; ???width: 100px; ???height: 100px; ???background: red; ???color: white; ?} ???#one { ???position: relative; ???top: 40px; ???left: 40px; ???background: blue; ?}
absolute
该元素位置相对于已定位的最近的父元素,若父元素不在,则相对于ICB(初始包含块)。absolute定位的元素与其它元素重叠。
效果
HTML
<!DOCTYPE html><html> ???<head> ???????????<meta charset="utf-8"> ???????????<title>absolute</title> ???????????<link href="absolute.css" rel="stylesheet" type="text/css" > ???</head> ???<body> ???????????<h1>展示absolute的用法。</h1> ???????????<p>这是第一段。</p> ???????????<p class="positioned">哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈啊哈。。。 </p> ???????????<p>kkkkkkkkkkkkkkkkkk。。。</p> ???????????<p>凑字数 <span>不凑字数</span> 凑字数<span>不凑字数</span> 凑字数</p> ???????</body></html>
CSS
p { ?background: aqua; ?border: 3px solid blue; ?padding: 10px; ?margin: 10px;}span { ?background: red; ?border: 1px solid black;}.positioned { ?position: absolute; ?background: yellow; ?top: 30px; ?left: 30px;}
fixed
使用fixed属性,即使页面滚动,元素也不会移动。
CSS
.box { ?width: 100px; ?height: 100px; ?background: red; ?color: white;}#one { ?position: fixed; ?top: 80px; ?left: 10px; ?background: blue;}.outer { ?width: 500px; ?height: 300px; ?overflow: scroll; ?padding-left: 150px;}
sticky
顾名思义,元素就像粘着一样。依赖用户的滚动行为在“relative”和“fixed”之间切换。
它必须指定一个阈值(top、right、bottom、left至少其中一个)来使粘滞定位按预期方式进行,否则无法与相对定位区分。
HTML
<!DOCTYPE html><html><head><meta charset="utf-8"> <title>展示sticky元素用法</title> <style>div.sticky { ?position: -webkit-sticky; ?position: sticky; ?top: 0; ?padding: 10px; ?background-color: #cae8ca; ?border: 2px solid #4CAF50;}</style></head><body><p>滚动页面。</p><div class="sticky">sticky</div><div style="padding-bottom:2000px"> ?<p>roll</p> ?<p>roll</p> ?<p>roll</p> ?<p>roll</p> ?<p>roll</p> ?<p>roll</p></div></body></html>
关于对CSS ?position的理解
原文地址:https://www.cnblogs.com/Jaehwan/p/9691444.html