大家好,我是前端架构师,关注微信公众号【程序员大卫】免费领取前端精品资料。
本文将以以下结构为例,列举 5 种常见方法,实现子元素在父容器内的垂直水平居中。
页面基本结构
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSS元素垂直水平居中</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.box {
width: 200px;
height: 200px;
border: 1px solid red;
}
.child {
width: 60px;
height: 60px;
background-color: blue;
}
</style>
</head>
<body>
<div class="box">
<div class="child"></div>
</div>
</body>
</html>
那么页面渲染如下:
居中后页面渲染如下:
1. Flex 布局
.box {
display: flex;
justify-content: center;
align-items: center;
}
2. Flex 结合 margin:auto
.box {
display: flex;
}
.box .child {
margin: auto;
}
3. Grid 布局
.box{
display: grid;
align-content: center;
justify-content: center;
}
4. absolute 结合 transform
.box {
position: relative;
}
.box .child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
5. absolute 撑满结合 margin auto
.box {
position: relative;
}
.box .child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
总结
推荐在支持现代浏览器的项目中优先使用 Flex 或 Grid 布局,而绝对定位方式可作为兼容性需求时的备选方案。
最后
点赞👍 + 关注➕ + 收藏❤️ = 学会了🎉。
更多优质内容关注公众号,@前端大卫。