text-align的居中与justify详解

352 阅读1分钟

center居中对齐

text-align 可以对文本、图片进行居中显示,那么它对 div 盒子可以居中显示吗?它到底对什么元素才能居中?

text-align: center 对行内级盒子相对于它的块级父元素居中对齐

  <style>
    .box {
      background-color: #F00;
      height: 300px;
      text-align: center;
    }

    .content {
      background-color: #0f0;
      height: 200px;
      width: 200px;

      /* 转成行内块 */
      display: inline-block;
    }
  </style>

  <div class="box">
    <div class="content"></div>
  </div>

image.png

justify两端对齐

justify 对最后一行没有用 如果希望最后一个有用需要使用 text-align-last

  <style>
    .box {
      width: 200px;
      background-color: red;
      color: #fff;
      text-align: justify;

      /* justify对最后一行没有用 如果希望最后一个有用需要使用text-align-last */
      text-align-last: justify;
    }
  </style>

  <div class="box">Container queries enable you to apply styles to an element based on the size of the element's
    container. If, for example</div>

image.png

  • 添加 text-align-last

image.png