Ryan King Ryan King - 3 months ago 5
CSS Question

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
height
s and
width
s(in pixels), so can anyone explain how to align the text horizontally without including a specified width and height?

Answer

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>