CSS中的各种居中

发布时间 2023-12-26 09:30:06作者: 且行且思

在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;