在CSS布局时经常会需要实现水平居中,垂直居中,水平垂直居中这样的要求但是却又不是非常的在意,所以总结一下。
文本水平居中
1.使用text-align属性:将容器的text-align属性设置为"center",可以使文本在容器中水平居中。
<style> .container { width: 500px; height: 500px; border: solid 1px black; text-align: center; /*将文本水平居中*/ } </style> <body> <div class="container">你好世界</div> </body>
2.使用display: flex和justify-content属性将容器内的内容水平居中。
<style> .container { width: 500px; height: 500px; border: solid 1px black; display: flex; /* 将容器设置为弹性盒子 */ justify-content: center; /* 将弹性盒子内的内容水平居中 */ } </style> <body> <div class="container">你好世界</div> </body>
3.使用display: table和margin属性将容器内的内容水平居中。
<style> .container { width: 500px; height: 500px; border: solid 1px black; display: table-cell; /* 将容器设置为表格单元格 */ text-align: center; /* 将文本水平居中 */ } </style> <body> <div class="container">你好世界</div> </body>
4.使用transform属性将文本水平垂直居中。
<style> .container { width: 500px; height: 500px; border: solid 1px black; position: relative; /* 将容器设置为相对定位 */ } .container p { position: absolute; /* 将文本设置为绝对定位 */ left: 50%; /* 将文本的左侧距离容器宽度的一半对齐 */ transform: translateX(-50%); /* 将文本水平垂直居中 */ } </style> <body> <div class="container"> <p>你好世界</p> </div> </body>
Tailwind CSS Justify Content
Justify Content
用于控制 flex 和 grid 项目如何沿着容器的主轴定位的功能类。
Class
|
Properties
|
---|---|
justify-start | justify-content: flex-start; |
justify-end | justify-content: flex-end; |
justify-center | justify-content: center; |
justify-between | justify-content: space-between; |
justify-around | justify-content: space-around; |
justify-evenly | justify-content: space-evenly; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
2018-12-26 Asp.Net : Page.RegisterStartupScript及 不执行的原因