Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
思路
“水平垂直居中”,一个老生常谈的话题了,在面试中出现的频率也是非常高。其实很简单,不要想着一下子就实现水平垂直居中,把这个问题拆成“水平居中” + “垂直居中”,从两个方向上去实现就容易多了。
行内元素很简单,水平方向设置text-align: center
,垂直方向设置line-height
,今天我们把重点放在块级元素上。
方法
简单整理了下,常用的有如下几种方式:
absolute
+margin
absolute
+calc
absolute
+transform
- 转行内元素
table-cell
flex
grid
实现
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>水平垂直居中</title>
</head>
<style>
.container {
width: 300px;
height: 300px;
background: #ccc;
}
.box{
width: 100px;
height: 100px;
background: #ff7433;
}
</style>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
absolute + margin
方法1:
.container {
position: relative;
}
.box{
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
方法2:
.container {
position: relative;
}
.box{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
absolute + calc
.container {
position: relative;
}
.box {
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
absolute + transform
.container {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
转行内元素
.container {
text-align: center;
line-height: 300px;
}
.box {
display: inline-block;
vertical-align: middle;
}
table-cell
.container {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
display: inline-block;
}
flex
方法1:
.container{
display: flex;
align-items: center;
justify-content: center;
}
方法2:
.container {
display: flex;
justify-content: center;
}
.box {
align-self: center;
}
grid
方法1:
.container {
display: grid;
justify-items: center;
align-items: center;
}
方法2:
.container {
display: grid;
}
.box {
justify-self: center;
align-self: center;
}
方法3:
.container {
display: grid;
justify-items: center;
}
.box {
align-self: center;
}
方法4:
.container {
display: grid;
align-items: center;
}
.box {
justify-self: center;
}
结果
总结
实现方式多种多样,光看的话可能没什么印象,动手敲一敲可能会事半功倍。
像这种问题,面试官考察的重点可能不光是如何实现水平垂直居中,有哪些实现方式才是考察的重中之重,不仅考察了你能不能实现这个需求,更多的其实是考察你对css的熟练程度。来面试的可能90%的人能答出3种,而你能答出6种,7种,这无疑就给你加了不少分了。
所以,我们平时要注意多思考,多总结,多尝试。同一个问题,我们要尝试用不同的方法去实现,去解决。问题不重要,方法和思路才是重点。