text-align揭秘

125 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        background-color: #f00;
        height: 300px;
      }
      .content {
        background-color: #0f0;
        height: 200px;
        width: 200px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="content"></div>
    </div>
  </body>
</html>

image.png

提问:如果想让绿色方块居中该怎么做?

方法一:使用text-align: center

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        background-color: #f00;
        height: 300px;
        text-align: center;
      }
      .content {
        background-color: #0f0;
        height: 200px;
        width: 200px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="content"></div>
    </div>
  </body>
</html>

很遗憾,这样并不能成功。至于为啥不生效呢?我们可以看看W3C对于text-align的描述:The text-align property describes how inline-level content of a block container is aligned,即text-align 属性描述了块容器的内联级内容如何对齐。

这下谜底就揭晓了,因为div是块级元素所以无法生效。

那么我们有什么办法使绿色方块居中呢?

方法二:使用display: inline-block将绿色方块变为内联级元素

.box {
    background-color: #f00;
    height: 300px;
    text-align: center;
}
.content {
    background-color: #0f0;
    height: 200px;
    width: 200px;
    display: inline-block;
}

方法三:使用margin: 0 auto

.box {
    background-color: #f00;
    height: 300px;
}
.content {
    background-color: #0f0;
    height: 200px;
    width: 200px;
    margin: 0 auto;
}

方法二和方法三均可以达成绿色方块居中的效果

image.png