Brett Brett - 4 months ago 5x
CSS Question

Styling an element by ID works, by class does not

I'm working with twitter bootstrap tables and am trying to assign my own style (background color) to a table's elements.

What works: assigning

to each <td> element, and then placing
#foo { ... }
in my stylesheet.

What doesn't work: assigning
to each <td> element, and then placing
.foo { ... }
in my stylesheet. I have also tried styling by placing
td { ... }
tr td { ... }
in my stylesheet. Neither worked.

Why could this be? I thought maybe there could be a class of the same name lying around, but unless bootstrap has a class called ".asdfasdfasdfasdf" I'm pretty sure that isn't the case.


Without seeing any actual code it's hard to tell, but I guess you have a CSS rule with a higher specificity that overrides your class. To track something like that use "inspect" in your browser to see which rule is overwriting your CSS class.

CSS precedence does work and is ordered like this:

  • Element, Pseudo Element: 0,0,0,1
  • Class, Pseudo class, Attribute: 0,0,1,0
  • Id: 0,1,0,0
  • Inline Style: 1,0,0,0

For example: If you have a rule like #body table tr td {} it will always have a higher precedence than tr td {} even than body table tr td {} or tr td.someClass {}.

You can read more about the specificity on this page: Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade.