Home >Web Front-end >CSS Tutorial >How do I center text both horizontally and vertically in an HTML table?

How do I center text both horizontally and vertically in an HTML table?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 00:50:02644browse

How do I center text both horizontally and vertically in an HTML table?

Aligning Text in an HTML Table Horizontally and Vertically

In an HTML table, centering the text within each cell, both horizontally and vertically, can enhance the presentation and readability of your data. Here's a detailed guide to achieve this:

Horizontal Alignment

To center the text horizontally, use the text-align CSS property. Add text-align: center; to the style attribute of the elements. This will align the text in the center of each cell.

Vertical Alignment

For vertical alignment, apply the vertical-align CSS property. Set vertical-align: middle; to ensure that the text is vertically centered within the cells. This property may need to be adjusted based on the height of the cells.

Example with Inline Styling

You can use inline styles within the table to apply these alignments:

<code class="html"><table border="1">
  <tr>
    <td style="text-align: center; vertical-align: middle;">Text</td>
    <td style="text-align: center; vertical-align: middle;">Text</td>
  </tr>
</table></code>

Example with CSS Class

Alternatively, you can create a CSS class to apply the alignments:

<code class="css">.center-text {
  text-align: center;
  vertical-align: middle;
}</code>

And use it in the table:

<code class="html"><table border="1">
  <tr>
    <td class="center-text">Text</td>
    <td class="center-text">Text</td>
  </tr>
</table></code>

Remember, the specified height and width of the cells may affect the vertical alignment. Adjust the values as needed to achieve the desired result.

The above is the detailed content of How do I center text both horizontally and vertically in an HTML table?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn