——部分转译自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就比它强多了。
----------
absolutefixedsticky
本文详细解析了CSS中的五种定位方式:static、relative、absolute、fixed和sticky。通过具体实例展示了不同定位方式的效果,并对比了它们之间的区别。
3万+

被折叠的 条评论
为什么被折叠?



