元素居中

flex 布局使元素居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.box {
display: flex;
width: 500px;
height: 500px;
justify-content: center;
align-items: center;
background-color: greenyellow;
}

.center {
width: 100px;
height: 100px;
background-color: yellow;
}

绝对定位居中

1
2
3
4
5
6
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

固定/绝对定位

1
2
3
4
5
6
7
8
.center {
position: absolute/fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}