——部分转译自MDN;
position 常见的有static
,relative
, absolute
, fixed
几种。sticky
不常见,我们放在最后说。
先粗暴的上段代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="static/js/jquery.js"></script>
<title>
</title>
<style>
* {
margin: 0;
padding: 0;
}
.wrapper {
margin-top: 100px;
width: 80%;
border: 3px solid #ccc;
margin: 100px auto;
}
.absolute, .static, .fixed, .relative {
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
}
.container {
position: relative;
margin-top: 100px;
width: 80%;
margin-left: 10%;
height: 400px;
border: 2px solid #ddd;
}
.absolute {
position: absolute;
background-color: green;
top: 0px;
left: 0px;
}
.static {
position: static;
background-color: pink;
left: 100px;
top: 100px;
}
.fixed {
position: fixed;
background-color: yellow;
top: 0;
left: 0;
}
.relative {
position: relative;
top: 0px;
left: 0px;
background-color: #aA1A00;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="absolute">absolute 定位</div>
<div class="fixed">fixed定位</div>
<div class="static">static 定位</div>
<div class="relative">relative 定位</div>
</div>
</div>
</body>
</html>
static
默认的位置,不受
left、right、top、bottom、index
(对于index的忽略处理还是不太明白,有待解决)的影响。
意思就是说设置了static
的元素以默认的
文档流的位置出现,即使对它设置了left、right、top、bottom、index
也不会对它所处的位置造成影响。 参照前面的代码
.static {
position: static;
background-color: pink;
left: 100px;
top: 100px;
}
我们对static
设置的left, top
丝毫不起作用。所以如果你的样式中对某个元素设置了static
,就不要再费力的设置它的left
等等了。
———-
relative
relative
设置的是相对于它在文本流中默认的位置,进行定位。举例来说:
-当不对它的position
进行任何操作
-当设置它的position: relative; left: 0; top: 0;
两者是等义的。
设置了relative
后,仍保留它在文本流中默认的位置,由此可见relative
是个特别霸道的属性。,这就是所谓的占着茅坑不拉翔吧。这点absolute, fixed
就比它强多了。
----------
absolute
fixed
sticky