1. 定位(position)
相对定位: relative
绝对定位: absolute
固定定位:fixed
位置改变属性:
top
bottom
left
right
2. 相对定位
(1)位置改变相对于自身原本的位置
(2)不会脱离文档流
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
ul {
width: 100px;
border: 1px solid black;
}
li {
width: 50px;
height: 50px;
}
li:nth-child(1) {
background-color: aquamarine;
}
li:nth-child(2) {
background-color: blue;
position: relative;
top: 20px;
left: 20px;
}
li:nth-child(3) {
background-color: red;
}
</style>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>
3. 绝对定位
(1)默认情况下参考物是body
(2)直系父级元素用相对定位,找到第一个作为参考物
(3)脱离文档流
(4)父级相对定位,子级绝对定位
(5)绝对定位使内联元素支持宽高
(6)绝对定位元素宽度百分比相对于参考物宽度,而不是父级宽度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
ul {
position: relative;
margin: 100px auto;
width: 100px;
border: 1px solid black;
}
li {
width: 50px;
height: 50px;
}
li:nth-child(1) {
background-color: aquamarine;
}
li:nth-child(2) {
background-color: blue;
position: absolute;
top: 20px;
left: 20px;
}
li:nth-child(3) {
background-color: red;
}
</style>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>
4. 层级
绝对定位元素,越后面层级越高, 层级越大越优先显示
z-index: 1
5. 固定定位
fixed
固定在浏览器某个区域
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
background-color: pink;
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div></div>
</body>
</html>