CSS-元素居中

水平/垂直/水平垂直
flex/margin+position/table

水平居中

flex布局

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

text-align

对inline inline-block inline-table inline-flex都有效,用在父元素

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

对块元素,可以转为行内块,然后父元素text-align

将内部转为行内块然后外部text-align,这种方法也适用于内部多个块的情况

1
2
3
4
5
6
.child {
display: inline-block;
}
.parent {
text-align: center;
}

margin

定宽:左右margin

1
2
3
4
.child {
width: 100px; /* 确保内部块是定宽 */
margin: 0 auto;
}

内容宽:table+margin

子元素设置为块级表格,再将其水平居中

display: table在表现上类似block,但宽度为内容宽

1
2
3
4
.child {
display: table; /* 宽度为内容宽,根据内容自动调整宽高 */
margin: 0 auto;
}

内容宽:flex+margin

1
2
3
4
5
6
.parent {
display: flex;
}
.child {
margin: 0 auto;
}

定宽:子绝父相+margin

子绝父相,子元素设置左右距离均为0,然后加上margin auto,注意一定要给子元素设定宽度否则会自动撑满

1
2
3
4
5
6
7
8
9
10
.parent {
position: relative;
}
.child {
position: absolute;
width: 100px; /* 一定要有,否则自动计算的margin值会为0,而该子盒子宽度会撑满整行 */
left: 0;
right: 0;
margin: 0 auto;
}

position+(margin/transform)

主要指通过定位(子绝父相 / 子元素relative)将子元素向右移动父元素的一半,然后再向左移动自身的一半(translateX或负margin)

使用translateX无需子元素定宽,而使用负margin子元素必须定宽

translateX:子绝父相,向右移动子元素,距离为父容器的一半;再向左移动子元素的一半

1
2
3
4
5
6
7
8
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%; /* 向右移动父容器的一半 */
transform: translateX(-50%); /* 再向左移动自身的一半 */
}

负margin:子元素relative+负margin

1
2
3
4
5
6
.child {
width: 500px;
position: relative;
left: 50%; /* 向右移动parent的一半 */
margin-left: -250px; /* 向左移动自身的一半 */
}

垂直居中

flex布局

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

或者使用align-items

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

table+vertical-align

1
2
3
4
5
6
7
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}

vertical-align只对inline和table-cell有效

单行inline:height=line-height

position+(margin/transform)

水平垂直居中

flex

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

或者直接

1
2
3
4
5
6
.parent {
display: flex;
}
.child {
margin: auto;
}

table

1
2
3
4
5
6
7
8
.parent {
display: table;
text-align: center;
}
.child {
display: table-cell;
vertical-align: middle;
}

position+(margin/transform)

margin

同前margin部分,如果要使用margin+子绝父相则必须要子元素定宽高,垂直方向父元素也要定高

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.parent {
position: relative;
height: 500px; /* 必须定高,否则子元素绝对定位撑不起父元素 */
}
.child {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
height: 100px;
width: 100px;
}