1. 四种定位的特性:
定位 | 参考物 | 特点 |
static | 默认 | 默认 |
相对定位relative | 定位前的位置 | 1.不影响元素本身特性 2.元素不脱离文档流 3.相对于原位置进行偏移 |
绝对定位 absolute | 最近的使用了定位的父级,如果没有找body | 1.元素脱离文档流 2.行元素支持所有css样式 3.块元素内容撑开高度 4.清楚子级浮动 |
固定定位fixed | 浏览器窗口 | 1.脱离文档流 2.清楚子级浮动 |
定位的作用:可以使用偏移描述:left、top、right、bottom
可以使用z-index提升层级
2.万能居中技巧:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
.div1{
width: 400px;
position: fixed;
height: 400px;
background-color: pink;
}
.div1 .div2{
background-color: gold;
width: 200px;
height: 200px;
/* 万能居中公式 */
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
</style>
</head>
<body>
<div class="div1">
<div class="div2"></div>
</div>
</body>
</html>
即:
当对子级使用相对定位时,子级对父级左和上的距离各为50%;同时margin-left和margin-top各为
子级宽高的二分之一;