What is CSS table alignment?
Table alignment here doesn’t mean reversing the tables up and down. It means to set the position of the text inside the columns <th> tag and rows <td> tag.
Alignment types
The two common table alignments are as follows:
- Horizontal alignment
- Vertical alignment
Let's understand them one by one and learn how to implement them.
1. Horizontal alignment
Horizontal alignment is known as the text-align property in <th> and <td> elements to the right, left, and center.
Syntax
- For Right:
text-align:right; - For Left:
text-align:left; - For Center:
text-align:center;
Note: Default values of the table head
<th>are center-aligned and the values of table data<td>cells are left-aligned.
2. Vertical alignment:
Vertical alignment is known as the vertical-align property in CSS. With this, we can set the vertical alignment of the content of <th> and <td> tags as top, bottom, and middle.
Note: Default values of table head and table data contents are middle aligned.
Syntax
- For Top:
vertical-align: top - For Bottom:
vertical-align: bottom - For Middle:
vertical-align: middle
Example
For this, we have to construct a table first. The code for constructing a table is given below:
Explanation
- Lines 2–3: We add universal styling to the table, its head, and cells. Then we define the border width type and color to be
2px,solid, andbluerespectively. - Lines 5–6: We define the width of the table to be
80%. This can be changed according to the needs and screen sizes. - Lines 8–10: We define the vertical alignment property along with cell height. Here
vertical-alignis equal to the bottom meaning the content will be at the bottom of the cell. - Lines 12–13: We define the horizontal alignment property here. Then we fix the text of the header to be on the right side(
text-align: right;). - Line 15: Don't forget to close the
styetag before theheadtag.