主题
垂直居中
⽔平居中
行内元素
- 设置⽗元素
text-align:center
块级元素,定宽
margin :
margin: auto
绝对定位
css.parent { position: relative; } .child { position: absolute; left: 50%; width: 100px; margin-left: -50px; /* 自身宽度的一半 */ } /* 可简写 */ .child { position: absolute; left: calc(50% - 50px); width: 100px; }
块级元素,不定宽
绝对定位 + translate
css.parent { position: relative; } .child { position: absolute; left: 50%; transform: translateX(-50%); }
flex
css.parent { display: flex; justify-content: center; } /* 下面这种也行 */ .parent { display: flex; margin: auto; }
垂直居中
定高
绝对定位
css.parent { position: relative; } .child { position: absolute; top: 50%; height: 100px; margin-top: -50px; } /* 可简写 */ .child { position: absolute; top: calc(50% - 50px); height: 100px; }
margin
css.parent { position: relative; } .child { position: absolute; top: 0; bottom: 0; height: 100px; margin: auto; }
不定高
父级使用
table-cell
布局,指定vertical-align
属性为middle
绝对定位 + translate
css.parent { position: relative; } .child { position: absolute; top: 50%; transform: translateY(-50%); }
flex
css.parent { display: flex; align-items: center; }
垂直水平居中
定宽定高
- 绝对定位 +
top、left、right、bottom
都为0
+margin:auto
css
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 100px;
height: 100px;
margin: auto
}
- 绝对定位 +
top、left
为50%
+margin
各自的一半
css
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-left: -50px;
margin-top: -50px;
}
/* 可简写 */
.child {
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
width: 100px;
height: 100px;
}
不定宽高
- 绝对定位+
top、left
为50%
+translate(-50%, -50%)
css
.parent {
position: relative;
width: 300px;
height: 300px;
}
.child {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
transform: translate(-50%, -50%);
}
table-cell
css
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child {
display: inline-block;
}
flex
css
.parent {
display: flex;
justify-content: center;
align-items: center;
}
grid
css
.parent {
display: grid;
justify-self: center;
align-self: center;
}