CSS垂直居中方案
CSS 中实现垂直居中的方法有很多,适用于不同的布局场景(如:行内元素、块级元素、Flex、Grid等)。以下是常见的几种方法,并按使用场景分类整理:
🔹 flex 布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.flex_div{
/* display: flex; */
background-color: aquamarine;
height: 200px;
width: 200px;
}
</style>
</head>
<body>
<div class="flex_div"></div>
</body>
</html>
🔹 grid 布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.grid_div {
height: 200px;
width: 200px;
background-color: chocolate;
}
.grid_div1 {
height: 100vh;
display: grid;
align-items: center;
justify-items: center;
}
</style>
</head>
<body>
<div class="grid_div1">
<div class="grid_div">
</div>
</div>
</body>
</html>
🔹 早期 table 布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
body {
height: 100vh;
width: 100vw;
display: table;
}
.table {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.table_cell {
display: inline-block;
height: 200px;
width: 200px;
background-color: chartreuse;
}
</style>
<body>
<div class="table">
<div class="table_cell"></div>
</div>
</body>
</html>
🔹 绝对定位 + Transform
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
html {
background-color: aqua;
}
.margin {
height: 200px;
width: 200px;
background-color: bisque;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
<body>
<div class="margin">
</div>
</body>
</html>
🔹 绝对定位 + Transform
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
html {
background-color: aqua;
}
.margin {
height: 200px;
width: 200px;
background-color: bisque;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
<body>
<div class="margin">
</div>
</body>
</html>
总结 🥇
| 父元素需要固定高度 | 方法 | 场景 | 是否推荐 |
|---|---|---|---|
| 需要 | Flex | 绝大多数场景 | ✅ 强烈推荐 |
| 需要 | Grid | 居中 + 多列布局需求 | ✅ 推荐 |
| 不需要 | transform + 绝对定位 | 弹窗、居中定位等 | ✅ 推荐 |
| 不需要 | margin + 绝对定位 | 弹窗、居中定位等 | ✅ 推荐 |
| 需要 | table-cell | 老浏览器兼容(IE等) | ⚠️ 过时写法 |