1. 使用【Flex 布局】
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}
2. 使用【Grid 布局】
.container {
display: grid;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}
3. 使用【Table 布局】
.container {
display: table;
}
.child {
display: table-cell;
text-align: center; /* 水平居中 */
vertical-align: middle; /* 垂直居中 */
}
4. 使用【絕對定位】+ 【transform 屬性】
.container {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
5. 使用【絕對定位】+ 【margin 屬性】 ——(僅適用于:已知元素寬高)
.container {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px; /* 其中50px是元素寬高的一半 */
}
單純的元素左右居中對齊:
塊級元素可以使用 magrin: 0 auto
;
非塊級元素使用 text-align: center;
文章來源地址http://www.zghlxwxcb.cn/news/detail-645111.html
文章來源:http://www.zghlxwxcb.cn/news/detail-645111.html
到了這里,關(guān)于【前端 | CSS系列】—— 第1篇:如何實現(xiàn)水平垂直居中對齊?的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!