【问题标题】:How to center text in a smaller div? [duplicate]如何在较小的div中居中文本? [复制]
【发布时间】:2016-07-24 13:00:56
【问题描述】:

是否可以在较小的 div 中水平居中文本?字符长度会随着时间而改变。所以不能为每个项目做一个偏移量。

参见示例:

.container {
  width: 100%;
  height: 50px;
  background: yellow;
}
a {
  width: 100px;
  height: 100px;
  margin: 0 50px;
  background: red;
  white-space: nowrap;
  float: left;
}
span {
  position: absolute;
  top: 0px;
  text-align: center;
}
<div class="container">
  <a href="" class="box-1">
    <span>Lorem</span>
  </a>
  <a href="" class="box-2">
    <span>Lorem ipsum dolor sit amet</span>
  </a>
  <a href="" class="box-3">
    <span>Lorem ipsum dolor sit</span>
  </a>
</div>

【问题讨论】:

  • 只需在锚点上使用text-align:center; 并删除跨度的绝对定位。
  • 看起来像 win 3.1 的热狗摊主题
  • here 这可能是你需要的。

标签: html css


【解决方案1】:

您可以在文本元素上使用left: 50%;,这会导致左边缘位于周围元素中心的位置。要更正此问题并将元素的中间定位在周围 div 的中心,您需要将一半的​​文本转换回左侧。您可以使用transform: translateX(-50%); 存档。此外,重要的是,周围的元素有position: relative;

您的示例如下所示:

.container {
  width: 100%;
  height: 50px;
  background: yellow;
}  

a {
    position: relative;
    width: 100px;
    height: 100px;
    margin: 0 50px;
    background: red;
    white-space: nowrap;
    float: left;
}
  
  span {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    text-align: center;
}
  <div class="container">
    <a href="" class="box-1">
      <span>Lorem</span>
    </a>
    <a href="" class="box-2">
      <span>Lorem ipsum dolor sit amet</span>
    </a>
    <a href="" class="box-3">
      <span>Lorem ipsum dolor sit</span>
    </a>
  </div>

【讨论】:

    【解决方案2】:

    使用中心标签。

    在您的示例中,您可以将中心标签放在 div 中,也可以将 div 居中。

    <center>
      <div class="container">
        <a href="" class="box-1">
          <span>Lorem</span>
        </a>
        <a href="" class="box-2">
          <span>Lorem ipsum dolor sit amet</span>
        </a>
        <a href="" class="box-3">
          <span>Lorem ipsum dolor sit</span>
        </a>
      </div>
    </center>

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 2019-09-16
      • 2015-03-02
      相关资源
      最近更新 更多