参考:https://zhuanlan.zhihu.com/p/29207938
https://blog.youkuaiyun.com/tengliu6/article/details/52088743
1、static(静态定位):默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。
2、fixed(固定定位):生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。可通过z-index进行层次分级。
3、relative(相对定位):生成相对定位的元素(相对于他原来应该在的位置),通过top,bottom,left,right的设置相对于其正常(原先本身)位置进行定位。可通过z-index进行层次分级。
4、absolute(绝对定位):生成绝对定位的元素(会脱离文档流),相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。可通过z-index进行层次分级。
主要演示relative和absolute
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="http://code.jquery.com/jquery-2.1.0.js"></script>
<style type="text/css">
#left {
background: #cccccc;
width: 200px;
height: 200px;
float: left;
}
#center {
background: #eee;
width: 200px;
height: 200px;
float: left;
}
#right {
background: #666666;
width: 200px;
height: 200px;
float: left;
}
#d2 #center {
position: relative;
top: 10px;
left: 10px;
}
#d3 #center {
position: absolute;
top: 10px;
left: 10px;
}
</style>
<title>Position</title>
</head>
<body>
<div style="width: 600px;">
<div id="d1">
<div id="left"></div>
<div id="center" class="c1">
<p>1 正常定位</p>
</div>
<div id="right"></div>
</div>
<div id="d2">
<div id="left"></div>
<div id="center" class="c2">
<p>2 relative定位:相对于应该在的位置偏移</p>
</div>
<div id="right"></div>
</div>
<div id="d3" style="position: relative;top:15px; ">
<div id="left"></div>
<div id="center" class="c3">
<p>3 absolute定位:给父级div设置relative可以让该div随父级相对固定</p>
</div>
<div id="right"></div>
</div>
</div>
</body>
<script>
window.onload = function() {
for (x = 1; x <= 3; x++) {
$(".c" + x).append("</br>" + $(".c" + x).offset().left + " " + $(".c" + x).offset().top);
console.log($(".c" + x).offset().left + " " +
$(".c" + x).offset().top);
console.log($(".c" + x));
}
}
</script>
</html>
效果如下图
定位左8上8是默认存在的
第一行是正常的
第二行position:relative
会导致center2在他应该在的位置偏移,仍然在文档流中。
#d2 #center {
position: relative;
top: 10px;
left: 10px;
}
第三行position:absolute
然后把他的父级div设置成非static并对父级top:15px,此处用relative。
可以看见center3脱离文档流,对应左上有偏移但是其top保证了10+15+8
#d3 #center {
position: absolute;
top: 10px;
left: 10px;
}