user6792199
user6792199

Reputation:

Horizontal Table aligning not working

Suppose I have some code like so...

table {
  text-align: center;
}
<table>
  <tbody>
    <tr>
      <td>Text</td>
    </tr>
    <tr>
      <td>Text</td>
    </tr>
    <tr>
      <td>Text</td>
    </tr>
  </tbody>
</table>

As you can see the text is not centering so far. However, when I add this code it is centering.

td {
  width: 1000px;
}

Can anyone explain me the reason why it is doing so?

Also, I do not want my code to be of specified heights and widths(in pixels), so can anyone explain how to align the text horizontally without including a specified width and height?

Upvotes: 1

Views: 117

Answers (2)

Yash Jain
Yash Jain

Reputation: 1

Your code is not centering because you do not have a specified height to your tds and when you do, you find your code working. If the td width is 1000px it is going to make your text go down 500px down the page.

And to answer the second part of your question, here are two ways you can solve the problem.

1.

table {
  text-align: center;
  margin: auto;
}
<table>
  <tbody>
    <tr>
      <td>Text</td>
    </tr>
    <tr>
      <td>Text</td>
    </tr>
    <tr>
      <td>Text</td>
    </tr>
  </tbody>
</table>

2.

table {
  text-align: center;
  width: 100%;
}
<table>
  <tbody>
    <tr>
      <td>Text</td>
    </tr>
    <tr>
      <td>Text</td>
    </tr>
    <tr>
      <td>Text</td>
    </tr>
  </tbody>
</table>

Upvotes: 0

StardustGogeta
StardustGogeta

Reputation: 3406

table {
  text-align: center;
  border: 2px solid blue;
}
<table onclick="this.style.width = '100%'">
  <tbody>
    <tr>
      <td>Text</td>
    </tr>
    <tr>
      <td>Text</td>
    </tr>
    <tr>
      <td>Text</td>
    </tr>
  </tbody>
</table>

This might help you see that the text is indeed centered, but the table is not expanding to the screen. Clicking the table will set the width to 100%, and will produce your expected output.

Upvotes: 2

Related Questions