静态定位
position:static;
相对定位
position:relative left:100px
①相对定位 以自己的左上角为基准点 移动
②相对定位移动后,位置仍然保留,是标准流,不脱标
绝对定位
position:absolute; top:0px; right:0px; bottom:0px; left:0px;
①以当前可见窗口左上角为基准点移动
②父亲有定位,以父亲的左上角为基准点移动
③父亲没有定位,爷爷有定位。以爷爷的左上角为基准点移动
注意:
加了定位和加了浮动的盒子 ,margin:0 auto;(居中对齐)就失效了,因为定位和浮动都是左对齐。
实现居中对齐的方法:
left:50%;(父盒子的一半) margin-left:盒子的一半(负值)
或者
top:50% (父盒子的一半) margin-top:盒子的一半(负值)
例如:
<!doctype html>
<html lang="en">
<head> <meta charset="UTF-8">
<title>Document</title>
<style>
.father { width: 300px; height: 300px; background-color: pink; margin: 100px auto; position: relative; }
.son { width: 50px; height: 50px; background-color: red; position: absolute; left: 50%; margin-left: -25px; }
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
<!doctype html>
<html lang="en">
<head> <meta charset="UTF-8">
<title>Document</title>
<style>
.father { width: 300px; height: 300px; background-color: pink; margin: 100px auto; position: relative; }
.son { width: 50px; height: 50px; background-color: red; position: absolute; left: 50%; margin-left: -25px; top: 50%; margin-top: -25px;}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>