如何将文本置于较小的div中?

时间:2016-04-04 20:07:06

标签: html css

是否可以将文本水平居中于较小的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>

2 个答案:

答案 0 :(得分:2)

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

您的示例如下所示:

&#13;
&#13;
.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;
}
&#13;
  <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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用中心标记。

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

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

相关问题