明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
随笔 - 1277, 文章 - 0, 评论 - 214, 阅读 - 320万
  博客园  :: 首页  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

CSS中的各种居中

Posted on   且行且思  阅读(46)  评论(0编辑  收藏  举报

在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;
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2018-12-26 Asp.Net : Page.RegisterStartupScript及 不执行的原因
点击右上角即可分享
微信分享提示