定位
- 指将指定的元素摆放到页面的任意位置
- 可选值
- static 默认值
- relative 相对定位
- absolute 绝对定位
- fixed 固定定位
1.绝对定位
- 开启绝对定位,元素会脱离文档流
- 开启定位后,如果不设置偏移量,元素位置不会发生变化
- 绝对定位是相对于其最近的开启了定位的祖先元素来进行定位的,
如果所有祖先元素没有开启定位,则会相对于浏览器窗口进行定位
一般情况,开启了子元素的绝对定位都会同时开启父元素的相对定位 - 绝对定位会使元素提升一个层级
- 绝对定位会改变元素的性质,内联元素变成块元素,块元素的宽度和高度会默认被内容撑开
2.相对定位
- 开启相对定位后,不设置偏移量,元素位置不会发生变化
- 相对定位是相对于元素在文档流中原来的位置进行定位
- 相对定位的元素不会脱离文档流
- 相对定位会使元素提升一个层级
- 相对定位不会改变元素的性质
3.固定定位
- 固定定位也是一种绝对定位,不同的是:
固定定位永远都会相对于浏览器窗口进行定位,固定在浏览器窗口的某个位置,不会随滚动条滚动
<!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>02.绝对定位、相对定位、固定定位的区别</title>
<style>
body {
display: flex;
justify-content: flex-start;
height: 900px;
}
.absoluteArea {
width: 400px;
height: 320px;
box-sizing: border-box;
padding:10px;
border: 3px solid #000;
position: relative;
}
.box1 {
width: 100px;
height: 100px;
background-color: #1781b5;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 150px;
left: 90px;
}
.box2{
width: 100px;
height: 100px;
background-color: #55bb8a;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
}
.relativeArea {
width: 400px;
height: 320px;
border: 3px solid #000;
box-sizing: border-box;
padding:10px;
margin-left: 10px;
}
.box3{
width: 100px;
height: 100px;
background-color: #1781b5;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
position: relative;
top: 30px;
left: 60px;
}
.box4{
width: 100px;
height: 100px;
background-color: #55bb8a;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
}
.fixedArea {
width: 400px;
height: 320px;
border: 3px solid #000;
box-sizing: border-box;
padding:10px;
margin-left: 10px;
}
.box5{
width: 100px;
height: 100px;
background-color: #1781b5;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
position: fixed;
top:150px;
left: 920px;
}
.box6{
width: 100px;
height: 100px;
background-color: #55bb8a;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="absoluteArea">
<h3>绝对定位</h3>
<div class="box1">
<h4>盒子一</h4>
</div>
<div class="box2">
<h4>盒子二</h4>
</div>
</div>
<div class="relativeArea">
<h3>相对定位</h3>
<div class="box3">
<h4>盒子三</h4>
</div>
<div class="box4">
<h4>盒子四</h4>
</div>
</div>
<div class="fixedArea">
<h3>固定定位</h3>
<div class="box5">
<h4>盒子五</h4>
</div>
<div class="box6">
<h4>盒子六</h4>
</div>
</div>
</body>
</html>