版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010011236/article/details/85146432
一、基本概念
position:用于指定一个元素在文档中的定位方式。并且由top, right, bottom, left 属性决定该元素的最终位置。
根据其取值不同可以有不同的定位方式:
- static:默认值,没有定位效果,按照正常的情况出现在文档中。
- relative:相对于元素正常显示的位置进行偏移。
- absolute:绝对定位有两种情况:
1.当祖先元素 position:relative 时,后代元素相对于祖先元素进行位置偏移;
2.当祖先元素没有设置 position 时,后代元素相对于整html文档进行位置偏移。 - fixed:相对于浏览器窗口进行定位。
- sticky:粘性定位可以被认为是相对定位(relative)和固定定位(fixed)的混合。元素在跨越特定阈值前为相对定位,之后为固定定位。
二、例子
(1)relative
相对定位是以该元素在文档中正常出现的位置为参考位置进行偏移。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>元素定位测试</title>
<style>
.box1 {
display: inline-block;
width: 100px;
height: 100px;
background: red;
color: white;
}
.box {
display: inline-block;
width: 100px;
height: 100px;
background: red;
color: white;
}
#two {
position: relative;
top: 100px;
left: 100px;
background: blue;
}
</style>
</head>
<body>
<div class="box" id="one">one</div>
<div class="box" id="two">two</div>
<div class="box" id="three">three</div>
</body>
</html>
代码1
由代码1的执行效果如图1所示,可以看出相对定位是以自身位置为参考进行移位的,同时不会改变其他元素的格式。
图1
(2)absolute
情况一:当祖先元素 position:relative 时,后代元素相对于祖先元素进行位置偏移。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>元素定位测试</title>
<style>
#parent {
position: relative;
width: 500px;
height: 400px;
background-color: #fafafa;
border: solid 3px #9e70ba;
font-size: 24px;
text-align: center;
}
#child {
position: absolute;
top: 40px;
right: 100px;
width: 200px;
height: 200px;
background-color: #fafafa;
border: solid 3px #783382;
font-size: 24px;
text-align: center;
}
</style>
</head>
<body>
<div id="parent">
<div id="child"></div>
</div>
</body>
</html>
代码2
代码2执行绝对定位的结果如图2所示。
图2
情况二:当祖先元素没有设置 position 时,后代元素相对于整html文档进行位置偏移。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>元素定位测试</title>
<style>
#child {
position: absolute;
top: 40px;
right: 100px;
width: 200px;
height: 200px;
background-color: #fafafa;
border: solid 3px blue;
font-size: 24px;
text-align: center;
}
</style>
</head>
<body>
<div id="parent">
<div id="child"></div>
</div>
</body>
</html>
代码3
代码3的绝对定位是以浏览器窗口为参考位置进行位置定位的。
(3)fixed
该元素的位置不会随着页面的滚动而发生改变。
(4)sticky
可以参考文献[3]。
参考文献
[1] https://dzone.com/articles/css-position-relative-vs-position-absolute
[2] https://developer.mozilla.org/zh-CN/docs/Web/CSS/position
[3]http://www.cnblogs.com/coco1s/p/6402723.html
https://www.jianshu.com/p/b72f504121f5