Styling Columns

From CSS Discuss

Jump to: navigation, search

A common request is to style table columns, and there are a number of ways to achieve this:

Contents

Classes

For example: <td class='name-column'>

Pro: Highly compatible with browsers Con: Lots of work, lots of markup

Adjacent sibling selectors

td { first (and second and 3rd and 4th etc) column styles } td + td { second (and 3rd and 4th etc) column styles } td + td + td { 3rd (and 4th etc) } td + td + td +td { 4th ...}

td + td td + td td + td td + td td + td td + td means "A <td> preceeded by a <td>", as the third cell in a row is preceeded by a cell, it applied to this.

td:first-child + td { 2nd (and only 2nd) column style }

This is a <td> preceeded by a <td> that is the first element in the parent element. The third cell is preceded by a cell, but not by the first child of the parent.

Pro: Separates style from content Con: Not supported by Internet Explorer, will get confused if any TDs span columns.

<col> and <colgroup> elements

col { styles here }

Pro: Easy and supported by MSIE Con: Only supported limited styles (width, border, background and visibility - with conditions). Not supported by Firefox. (Which parts not supported in Firefox? I get it to work)

See also: http://ln.hixie.ch/?start=1070385285&count=1

Combining the methods

Place COLGROUP and COL elements in your table, give the COLs you want to style a class. Now you can select the cell with both selectors, but they must be in completely separate rulesets for IE to work (the selectors can't be combined with a comma, because IE chokes on the adjacent sibling (+) selector and ignores the ruleset):

  1. myTable td:first-child + td + td { /* for CSS2 browsers */
  /* column 3 styles */

}

  1. myTable .col3 { /* separate ruleset for IE */
  /* column 3 styles */

}

Javascript Assistance

See Script Hacks for some more table styling options

You can find a lot more help on this topic at http://www.webscriptexpert.com/

Personal tools