面试常考题,先说结论,再上代码示例。
- 移动端,推荐 flex
- PC 端,没有兼容要求,推荐 flex;
- PC 端,大小固定,推荐负 margin;
- PC 端,大小不固定,推荐 table-cell 和 transform;
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>水平垂直居中</title>
<style>
.outer {
width: 200px;
height: 200px;
margin: 10px;
background: #999;
position: relative;
}
.inner {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
background: lightblue;
}
/* 要求子元素固定大小 */
.margin-center {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
/* 要求子元素固定大小 */
.margin-auto {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
/* 要求子元素固定大小 */
.calc-center {
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
/* 要求容器元素固定高度 */
.line-height-center {
line-height: 200px;
text-align: center;
}
.line-height-center .inner {
display: inline-block;
}
/* 兼容性好,推荐使用 */
.table-center {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.table-center .inner {
display: inline-block;
}
/* 不要求子元素固定大小,兼容性一般 */
.transform-center {
position: absolute;
top: 50%;
left: 50%;
transform: translateY(-50%) translateX(-50%);
}
/* 不要求子元素固定大小,兼容性一般,移动端首选 */
.flex-center {
display: flex;
justify-content: center;
align-items: center;
}
/* 类似flex,兼容性不如flex,不推荐使用 */
.grid-center {
display: grid;
}
.grid-center .inner {
align-self: center;
justify-self: center;
}
</style>
</head>
<body>
<h2>要求子元素固定大小</h2>
<div class="outer">
<div class="inner margin-center">margin</div>
</div>
<div class="outer">
<div class="inner margin-auto">auto</div>
</div>
<div class="outer">
<div class="inner calc-center">calc</div>
</div>
<div class="outer line-height-center">
<div class="inner">line-height</div>
</div>
<div class="outer table-center">
<div class="inner">table</div>
</div>
<h2>不要求子元素固定大小</h2>
<div class="outer">
<div class="inner transform-center">transform</div>
</div>
<div class="outer flex-center">
<div class="inner">flex</div>
</div>
<div class="outer grid-center">
<div class="inner">grid</div>
</div>
</body>
</html>