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
Release: 2024-11-03 00:50:02
Original
642 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template