CSS各种居中

水平居中

内联元素(inline or inline-*)例如<img>或者<a>

居中方法:相对父级块级元素居中对齐

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

demo:

See the Pen QEZdYO by abcdGJJ (@abcdGJJ) on CodePen.

块级元素(block)

居中方法:在设置宽度的前提下,设置margin-left和margin-right为auto让它居中

1
2
3
.center-me {
margin: 0 auto;
}

demo:

See the Pen WxVRmk by abcdGJJ (@abcdGJJ) on CodePen.

很多块级元素在一行

居中方法:更改display为inline-block或者使用flex布局来实现

demo:

See the Pen JKgEqQ by abcdGJJ (@abcdGJJ) on CodePen.

还是flex布局比较省事

垂直居中

内联元素

单行文本

设置相等的上下padding

demo:

See the Pen rLXjEA by abcdGJJ (@abcdGJJ) on CodePen.

在文本不会换行的情况下,可以使用line-height,让其与height相等去对齐文本

demo:

See the Pen EyqWYJ by abcdGJJ (@abcdGJJ) on CodePen.

多行文本

可以利用上下等padding的方式让多行居中,但是如果这方法没用,你可以让这些文字的容器按table-cell模式显示,然后设置文字的vertical-align属性对齐

demo:

See the Pen pbrZoK by abcdGJJ (@abcdGJJ) on CodePen.

如果不想设置table-cell模式,可以试试flex

1
2
3
4
5
6
.flex-center-vertically {
display: flex;
justify-content: center;//居中
flex-direction: column;//flex方向
height: 400px;
}

块级元素

已知宽高

定位+负边距

demo:

See the Pen NAQpqX by abcdGJJ (@abcdGJJ) on CodePen.

未知宽高

定位 + transform

demo:

See the Pen VjopvZ by abcdGJJ (@abcdGJJ) on CodePen.

或者使用flexbox

1
2
3
4
5
.parent {
display: flex;
flex-direction: column;
align-items: center;
}

水平垂直居中

固定宽高

先绝对居中,然后运用负边距

demo:

See the Pen VjopZZ by abcdGJJ (@abcdGJJ) on CodePen.

宽高未知

使用transofrm属性在两个方向都平移负50%

demo:

See the Pen vKoxGX by abcdGJJ (@abcdGJJ) on CodePen.

或者使用flex

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