In a page I have many HTML tables that have many columns in them. I need to apply different styles on them. All columns will have different width but in tables they will same, by this I mean first column of all tables will be same, same is for second and all columns.
CSS is applied on tables but not on columns, is there a way I just add css classes and I may have not to apply them in html code and they are applied automatically. May be using
pseudocolumns or any other way ?
If you’re able to use browsers that support CSS
nth-child(), you can use:JS Fiddle demo.
In the above demo I’ve used
:nth-child(even)to avoid styling the first of thetdelements (which contains the row-heading), you could, of course, contain the row heading in athelement (which would probably be more semantically correct), or, to style theoddcolumns (or theoddtdelements) but not the:first-child, the:not()selector is available:JS Fiddle demo.
If you’re limited by having to support older browsers, that don’t support the
:nth-child()pseudo-class, you can use the adjacent-sibling selector (though this is less maintainable):JS Fiddle demo.
Thoug it’d be easier to style with classes (even if only provided for the
odd(or theeven):You could also use the
colgroupandcolelements to define classes for your columns:With the following CSS as an example (note there’s no reason not to style the other
colclasses, I just chose not to in this demo):JS Fiddle demo.
References:
+) combinator.col.colgroup.:first-child.:not().:not()compatibility, at Quirksmode.:nth-child().:nth-child()compatibility, at Quirksmode.