AlwaysLearning
AlwaysLearning

Reputation: 8041

Centering makes the table narrow

I am centering a table as follows:

<div class="center-box">
  <table>
    <tr>
      <td>
        <h1>Some text.</h1>
      </td>
      <td>
        <h1>Why does this line get wrapped? Why does this line get wrapped?</h1>
      </td>
    </tr>
  </table>
</div>

Here is the CSS:

.center-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

For some reason, the table no longer occupies 100% of the viewport width. Here is the Fiddle.

UPDATE 1: Following the reply suggesting to use flex, I produced the linked example, for which that approach is not working so far.

Upvotes: 0

Views: 51

Answers (1)

Alohci
Alohci

Reputation: 83051

Because you've halved the available width of the table's container by setting left to 50%. Right computes to 0. So what's remaining between left and right is just the other 50%.

Solution is to use a better centering method, like flexbox.

.center-box {
  position: absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  display:flex;
  justify-content:center;
  align-items:center;
}
<div class="center-box">
  <table>
    <tr>
      <td>
        <h1>Some text.</h1>
      </td>
      <td>
        <h1>Why does this line get wrapped? Why does this line get wrapped?</h1>
      </td>
    </tr>
  </table>
</div>

Upvotes: 2

Related Questions