在面试中或者日常工作中经常会遇到需要实现水平垂直居中的场景,现在给大家介绍一下几种容易实现的方法。
<!-- html代码 -->
<div class="container">
<div class="content">content</div>
</div>
水平垂直居中
- 我最喜欢用的
flex
布局
.container {
background-color: #000;
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.content {
width: 200px;
height: 200px;
background-color: red;
}
grid
布局
.container {
background-color: #000;
height: 100vh;
display: grid;
}
/* 方案1 */
.content {
width: 200px;
height: 200px;
background-color: red;
margin: auto;
}
/* 方案2 */
.content {
width: 200px;
height: 200px;
background-color: red;
justify-self: center;
align-self: center;
}
- 利用
position
和transform
- 绝对定位:适用于不知道父元素的宽度和高度,也不知道自己的宽度和高度
.container {
position: relative;
}
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- 相对定位:父元素设置了高度,且父元素下只有一个元素
.container {
height: 100vh;
}
.content {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
absolute
+calc
.container {
position: relative;
}
.content {
position: relative;
width: 100px;
height: 100px;
left: calc(50% - 50px);
top: calc(50% - 50px);
}
absolute
+ 负margin
.container {
position: relative;
}
.content {
position: relative;
width: 100px;
height: 100px;
left: 50%;
top: 50%;
margin-left: -50px;
margin-right: -50px;
}
table-cell
, 需要设定父元素的宽度
- 配合
margin: auto
.container {
height: 100vh;
width: 100vw;
display: table-cell;
vertical-align: middle;
}
.content {
background-color: red;
width: 100px;
display: block; /* 还可以是 table | flex | grid,但不能是 inline-xxx */
margin: 0 auto;
}
- 配合
text-align
.container {
height: 100vh;
width: 100vw;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.content {
background-color: red;
display: inline-block;
}
水平居中
以下几种只实现水平居中
margin: auto
, (注:需要固定元素的宽度)
.content {
background-color: red;
width: 400px;
margin: 0 auto;
}
text-align
+inline-block
.container {
text-align: center;
}
.content {
display: inline-block;
text-align: left; /* 重置文字位置(如果需要) */
}
fit-content
+margin
- 直接应用于元素上, 缺点:会使元素的宽度改变(同内容宽度)。
.content {
width: fit-content;
margin: auto;
}
- 应用于元素的父元素上,优点:即使子元素是浮动元素也适用。
.container {
height: 100vh;
width: fit-content;
margin: auto;
}
垂直居中
以下几种只实现垂直居中的情况
table-cell
+vertical-align
, 该方案可配合水平居中的方案 1、2,实现水平垂直居中
.container {
display: table-cell;
vertical-align: middle;
}
inline-block
+line-height
缺点:需要知道其父元素高度。
优点:不需要固定居中元素的高。
该方案可配合水平居中的方案2
,实现水平垂直居中
.container {
background-color: green;
height: 300px;
line-height: 300px;
}
.content {
background-color: red;
line-height: initial; /* 重置 */
vertical-align: middle;
display: inline-block;
}
inline-block
+vertical-align
该方案可配合水平居中的方案2
,实现水平垂直居中
.container {
background-color: green;
height: 300px;
}
.container::after {
content: "";
display: inline-block;
vertical-align: middle;
height: 100%;
}
.content {
background-color: red;
display: inline-block;
vertical-align: middle;
}