Style the first <td> column of a table differently

CssCss SelectorsPadding

Css Problem Overview


If I have a table with two columns, how do I specify a padding or any other css so that it is applied just for the first column of <td>s. Also how do I style an n-th column similarly?

Css Solutions


Solution 1 - Css

You could use the n-th child selector.

to target the nth element you could then use:

td:nth-child(n) {  
  /* your stuff here */
}

(where n starts at 1)

Solution 2 - Css

If you've to support IE7, a more compatible solution is:

/* only the cells with no cell before (aka the first one) */
td {
    padding-left: 20px;
}
/* only the cells with at least one cell before (aka all except the first one) */
td + td {
    padding-left: 0;
}

Also works fine with li; general sibling selector ~ may be more suitable with mixed elements like a heading h1 followed by paragraphs AND a subheading and then again other paragraphs.

Solution 3 - Css

The :nth-child() and :nth-of-type() pseudo-classes allows you to select elements with a formula.

The syntax is :nth-child(an+b), where you replace a and b by numbers of your choice.

For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.

td:nth-child(3n+1) {  
  /* your stuff here */
}

:nth-of-type() works the same, except that it only considers element of the given type (

in the example).

For more information about nth-child https://developer.mozilla.org/es/docs/Web/CSS/:nth-child

Solution 4 - Css

This should help. Its CSS3 :first-child where you should say that the first tr of the table you would like to style. http://reference.sitepoint.com/css/pseudoclass-firstchild

Solution 5 - Css

To select the first column of a table you can use this syntax

tr td:nth-child(1n + 2){
  padding-left: 10px;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShalinView Question on Stackoverflow
Solution 1 - CssRRikeshView Answer on Stackoverflow
Solution 2 - CssFelipeAlsView Answer on Stackoverflow
Solution 3 - CssMS IbrahimView Answer on Stackoverflow
Solution 4 - CsstiantangView Answer on Stackoverflow
Solution 5 - CssSaptarshi BanerjeeView Answer on Stackoverflow