css水平垂直居中
这是一个很常见的样式布局,网上也有很多的实现方式,本文主要是针对一些比较常用到的方法做一下总结,记录一下。
现有实现方式大致的思路归纳为以下几种:
- 固定宽高居中
- absolute + margin auto
- absolute + 负 margin
- absolute + calc
- 不定宽高居中
- lineheight
- flex
- absolute + transform
- grid
- table-cell
公共代码(后面代码都基于这里)
<div class="out">
<div class="inner">水平垂直居中</div>
</div>
1
2
3
2
3
实现的效果:
# absolute + margin auto
.out {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;
}
.inner {
background-color: blueviolet;
width: 300px;
height: 300px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# absolute + 负 margin
.out {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;
}
.inner {
background-color: blueviolet;
width: 300px;
height: 300px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -150px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# absolute + calc
.out {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;
}
.inner {
background-color: blueviolet;
width: 300px;
height: 300px;
position: absolute;
top: calc(50% - 150px);
left: calc(50% - 150px);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# lineheight
.out {
width: 500px;
height: 500px;
border: 1px solid #000;
line-height: 500px;
text-align: center;
font-size: 0px;
}
.inner {
font-size: 16px;
background-color: blueviolet;
display: inline-block;
vertical-align: middle;
line-height: initial;
/* 若需要设置元素的宽高时 */
/* width: 300px;
height: 300px; */
text-align: center;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# flex
.out {
width: 500px;
height: 500px;
border: 1px solid #000;
display: flex;
justify-content: center;
align-items: center;
}
.inner {
background-color: blueviolet;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# absolute + transform
.out {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;
}
.inner {
background-color: blueviolet;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# grid
.out {
width: 500px;
height: 500px;
border: 1px solid #000;
display: grid;
}
.inner {
background-color: blueviolet;
align-self: center;
justify-self: center;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# table-cell
.out {
width: 500px;
height: 500px;
border: 1px solid #000;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.inner {
background-color: blueviolet;
display: inline-block;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
好了,基本上就这些了;还有些不怎么用到的就没去整理了。
- PC 端:考虑兼容性的话推荐使用 absolute+负 margin 和table-cell; 否则直接 flex。
- 移动端:首推flex。
上次更新: 2022/09/06, 10:30:04