新聞中心
?關(guān)于CSS實(shí)現(xiàn)內(nèi)容居中的方式有很多種,在今天這篇文章里,我給大家整理了8種實(shí)現(xiàn)內(nèi)容居中的方式,希望這些方法對(duì)你學(xué)習(xí)和使用CSS進(jìn)行開發(fā)有幫助。

1. Flex
可能是當(dāng)今最流行和最簡(jiǎn)單的居中方式,我可以放心地承認(rèn),當(dāng)我可以使用 text-align: center 代替時(shí),我使用它來(lái)對(duì)齊段落。
.flexbox-row {
display: flex;
flex-direction: row; /* default value */
justify-content: center; /* x-axis */
align-items: center; /* y-axis */
}如果您不知道自己在做什么,F(xiàn)lexbox 可能會(huì)有些混亂?;旧?justify-content 跨越 x 軸,align-items 跨越 y 軸。如果將 flex-direction 設(shè)置為 column,則軸將反轉(zhuǎn)。
.flexbox-col {
display: flex;
flex-direction: column;
justify-content: center; /* y-axis */
align-items: center; /* x-axis */
}這不是一個(gè) flexbox 的文章,所以,在這里不詳細(xì)介紹flexbox。
2. grid
這個(gè)也是非常實(shí)用的方法。
.grid {
display: grid;
place-items: center;
}
3. Flex/Grid + Margin auto
.margins {
display: flex; /* or grid */
}
.margins p {
margin: auto;
}
4. Text align
是的,這真的很容易。
p {
text-align: center;
}
5.Padding
如果你沒有固定的高度并且想要垂直居中,這可能是最簡(jiǎn)單的方法。
p {
padding: 80px 0;
}
6. Text align + Padding
這個(gè)方法的前提是,沒有設(shè)置固定高度,在這種場(chǎng)景下,使用這種方法也是非常實(shí)用簡(jiǎn)單的。
p {
text-align: center;
padding: 16px 0;
}
7.Absolute
這個(gè)方法也是非常實(shí)用的。
.box {
position: relative;
}
.box p {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
8.table
這個(gè)table雖然有點(diǎn)過(guò)時(shí)了,但是在一些表格實(shí)現(xiàn)文字內(nèi)容居中的時(shí)候,還是非常實(shí)用的。
.table {
display: table;
}
.table p {
display: table-cell;
text-align: center; /* x-axis */
vertical-align: middle; /* y-axis */
}
寫在最后
以上就是我今天跟你分享的8種CSS實(shí)現(xiàn)內(nèi)容居中的方法,如果你覺得有用的話,請(qǐng)記得點(diǎn)贊我,關(guān)注我,并將這篇文章分給你的朋友們,也許能夠幫助到他。?
文章題目:八種CSS實(shí)現(xiàn)內(nèi)容居中的方法
URL標(biāo)題:http://www.fisionsoft.com.cn/article/dpoihpd.html


咨詢
建站咨詢
