Ryan Shang

生死看淡,不服就干

0%

CSS水平居中

1. 行内元素

1
2
3
.parent {
text-align: center;
}

2. 块级元素

1
2
3
div {
margin: 0 auto;
}

3. 绝对定位(left+width)

1
2
3
4
5
6
7
8
9
10
.parent {
position: releative;
}

.child {
position: absolute;
width: X; /* X为一个绝对宽度 */
left: 50%;
margin-right: -0.5*X
}

4. 绝对定位(transform)

1
2
3
4
5
6
7
8
9
.parent {
position: releative;
}

.child {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}

5. Flex布局

1
2
3
4
.parent {
display: flex;
justify-content: center;
}

6. Grid布局

1
2
3
4
.parent {
display: grid;
justify-items: center;
}