CSS -position(定位)
目录
- 一、应用场景
- 二、定位参照物
- 三、案例
- 1.效果
- 2.代码实现
核心讲解relative/absolute/fixed
一、应用场景
- 元素出现位置
随意
,无实际的元素位置关系,位置天马行空
- 该元素
不会影响
其它元素的排列 - 结合平移/外边距实现元素在区域内的
水平垂直居中
举例:场景一
举例:场景三
二、定位参照物
- relative:元素会
相对于其正常位置
进行定位 - absolute:元素会
脱离正常的文档流
,并且相对于最近的已定位祖先元素
(即 position 值不为 static 的祖先元素)进行定位。如果没有找到已定位的祖先元素,则相对于html元素进行定位。 - fixed:元素会
脱离正常的文档流
,并且相对于浏览器窗口
进行定位
视口:视口通常是浏览器窗口中除去边框、菜单栏、地址栏和状态栏等之外的区域,用户可以通过调整浏览器窗口的大小来改变视口的尺寸。
三、案例
1.效果
为了更明显的对比出relative和absolute的定位参照,我们可以将boxs.position调整为absolute进行突出对比
2.代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>position</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container{
width: 500px;
height: 500px;
background-color:aqua;
margin: 100px;
}
.boxs{
width: 300px;
height: 300px;
background-color: red;
position: relative;
left: 50px;
top: 50px;
}
.box{
position: absolute;
top: 100px;
left: 100px;
width: 200px;
height: 200px;
background-color: rgb(29, 229, 29);
}
.bottomBox{
position: fixed;
bottom:0;
left: 0;
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
</head>
<body>
<div class="container">
<div class="boxs">
<div class="box"></div>
<div class="bottomBox"></div>
</div>
</div>
</body>
</html>