-1

Is it possible to horizontally center the text in a smaller sized div? The character length will change over time. So it's not an option to make an offset for each item.

See example:

.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>
Stickers
  • 75,527
  • 23
  • 147
  • 186
muchacho
  • 393
  • 5
  • 7

2 Answers2

4

You can use left: 50%; on the text element which results in a position where left edge is at the center of the surrounding element. To correct this and postion the middle of the element at the center of the surrounding div you need to transform half of the text back to the left. You can archieve this with transform: translateX(-50%);. Moreover it is important, that the surrounding element has position: relative;.

Your example would look like this:

.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>
0

Use the center tag.

With your example, you can either put the center tags inside the div, or center the 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>