前端常见的集中垂直居中的方式
建议 :先看结构后看样式 !
1:使用flex进行 垂直居中
<!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;
}
.Father {
display: flex; // 给父元素 设置为 flex 布局
justify-content: center;
// 该属性可以理解为 一个大盒子 里 对子盒子进行 水平居中 取值 还有 flex-start flex-end ....等等
详情请见文档 <br> https://www.runoob.com/w3cnote/flex-grammar.html
// 该属性可以理解为 一个大盒子 里 对子盒子进行 垂直居中 取值 还有 flex-start flex-end ....等等
详情请见文档 <br> https://www.runoob.com/w3cnote/flex-grammar.html
align-items: center;
width: 400px;
height: 400px;
background-color: skyblue;
}
.son {
width: 200px;
height: 200px;
background-color: slateblue;
}
</style>
</head>
<body>
// 公共结构 一个父元素 一个子元素
<div class="Father">
<div class="son"></div>
</div>
</body>
</html>
> 2:使用flex进行 垂直居中 第二种方式 给父盒子 设置 垂直居中 给 子盒子margin:0 auto 水平居中
>
> 公共样式
>
> <div class="Father"> // 父盒子
<div class="son"></div> /子盒子
</div>
CSS
.Father {
display: flex;
align-items: center;
width: 400px;
height: 400px;
background-color: skyblue;
}
.son {
width: 200px;
height: 200px;
margin: 0 auto
background-color: slateblue;
}
> 利用 > 子绝父相
> 公共样式
>
> <div class="Father"> // 父盒子
<div class="son"></div> /子盒子
</div>
.Father {
position: relative;
width: 400px;
height: 400px;
background-color: pink;
}
/* 方法3 */
/* .son {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
transform: translate(-50%, -50%);
background-color: purple;
} */
/* 方法二四
利用margin 返回
回踩 自身的宽高的一半 margin-left: -100px;
margin-top: -100px;
*/
/* .son {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin-left: -100px;
margin-top: -100px;
background-color: purple;
} */
方法 五
.son {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 200px;
height: 200px;
margin: auto;
background-color: purple;
}