八种CSS实现内容居中的方法
source link: https://www.51cto.com/article/742714.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
八种CSS实现内容居中的方法
关于CSS实现内容居中的方式有很多种,在今天这篇文章里,我给大家整理了8种实现内容居中的方式,希望这些方法对你学习和使用CSS进行开发有帮助。
关于CSS实现内容居中的方式有很多种,在今天这篇文章里,我给大家整理了8种实现内容居中的方式,希望这些方法对你学习和使用CSS进行开发有帮助。
1. Flex
可能是当今最流行和最简单的居中方式,我可以放心地承认,当我可以使用 text-align: center 代替时,我使用它来对齐段落。
.flexbox-row {
display: flex;
flex-direction: row; /* default value */
justify-content: center; /* x-axis */
align-items: center; /* y-axis */
}
如果您不知道自己在做什么,Flexbox 可能会有些混乱。基本上 justify-content 跨越 x 轴,align-items 跨越 y 轴。如果将 flex-direction 设置为 column,则轴将反转。
.flexbox-col {
display: flex;
flex-direction: column;
justify-content: center; /* y-axis */
align-items: center; /* x-axis */
}
这不是一个 flexbox 的文章,所以,在这里不详细介绍flexbox。
2. grid
这个也是非常实用的方法。
.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
如果你没有固定的高度并且想要垂直居中,这可能是最简单的方法。
p {
padding: 80px 0;
}
6. Text align + Padding
这个方法的前提是,没有设置固定高度,在这种场景下,使用这种方法也是非常实用简单的。
p {
text-align: center;
padding: 16px 0;
}
7.Absolute
这个方法也是非常实用的。
.box {
position: relative;
}
.box p {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
8.table
这个table虽然有点过时了,但是在一些表格实现文字内容居中的时候,还是非常实用的。
.table {
display: table;
}
.table p {
display: table-cell;
text-align: center; /* x-axis */
vertical-align: middle; /* y-axis */
}
以上就是我今天跟你分享的8种CSS实现内容居中的方法,如果你觉得有用的话,请记得点赞我,关注我,并将这篇文章分给你的朋友们,也许能够帮助到他。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK