Reputation:
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?
Upvotes: 1
Views: 117
Reputation: 1
Your code is not centering because you do not have a specified height to your td
s 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.
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>
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
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