How To Set Text-align For Whole Column Of HTML Table?

You cannot set text-align on a column element

(Well, you can, but it won't have any effect)

There are only a couple of properties that have an effect, namely border, background, width, and visibility.

If you need to style a column outside of those attributes, MDN notes some possible workarounds.

  • To achieve the same effect as the left, center, right or justify values:
    • Do not try to set the text-align property on a selector giving a <col> element. Because <td> elements are not descendant of the <col> element, they won't inherit it.
    • If the table doesn't use a colspan attribute, use the td:nth-child(an+b) CSS selector. Set a to zero and b to the position of the column in the table, e.g. td:nth-child(2) { text-align: right; } to right-align the second column.
    • If the table does use a colspan attribute, the effect can be achieved by combining adequate CSS attribute selectors like [colspan=n], though this is not trivial.

Eg.

table { width: 20em; table-layout: fixed; border-collapse: collapse; text-align: center; } td { border: black solid 0.1em; } td:nth-child(2) { text-align: left; }

jsfiddle

If you have greater control over the HTML generation, however, it is probably better to just add a class to the cells in question and style those.

posted over 4 years ago CC BY-SA 4.0 user card Moshi‭ 2436 reputation 16 37 280 55 Copy Link Raw Markdown History

1 comment thread

General comments (1 comment)

Từ khóa » Html Colspan Align Center