子绝父相-前端学习第十五天
子绝父相
场景:让子元素相对父元素进行移动
含义:
- 子元素:绝对定位
- 父元素:相对定位
优点:
- 父元素是相对定位,则对网页布局影响最小
子绝父绝
场景:父元素已经通过绝对定位摆放好了位置
案例:
<!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>
body{
background-color: #000;
}
.box{
/* 父相 */
position: relative;
width: 228px;
height: 270px;
margin: 100px;
background-color: #fff;
}
img{
/* 子绝 */
position: absolute;
top: 4px;
right: -4px;
}
</style>
</head>
<body>
<div class="box">
<p>我是第一段</p>
<img src="./images/hot.png" alt="">
<p>我是第二段</p>
</div>
</body>
</html>
水平垂直居中
实现步骤:
-
子绝父相
-
给子元素设置参考父元素向右移动向下移动50%距离
left:50%;
top50%
-
再利用margin-left和margin-top负自身一半,来实现最后居中
固定定位
介绍:死心眼型定位,相对于浏览器进行定位移动
代码:position:fixed;
特点:
1. 需要配合方位属性实现移动
2. 相对于浏览器可视区域进行移动
3. 在页面中不占位置→已经脱标
应用场景:让盒子固定在屏幕中的某个位置

浙公网安备 33010602011771号