Zachary Wright Zachary Wright - 17 days ago 4
CSS Question

Override CSS style

I am defining some CSS classes which, when applied to a table, will generate some default styling.

For example, lets say I create a class called myTable:

.myTable {
th {
background-color: #000;
}

td {
background-color: #555;
}
}


So any table with the .myTable class would get those colors on th and td by default.

I thought that if another class were to be assigned to an individual td, then it would override the default style.

So if I had another class:

.red { background-color: red; }


And a table:

<table class=myTable>
<th class="red">Content</th>
<td>Hello!</td>
</table>


I thought that the "red" class would cause the background of the header to be red, rather than black. That is not the case. In order for this class to override the original, it has to be defined within the myTable class like so:

td.red { background-color: red; }


Am I missing something here, is there another way to do this so that I could have default styles that are more easily overridden?

Answer

The idea is that which style to use depends on two things: how specific it the selector is, the position of rule (latest rule wins). Example:

p {
  background-color: red;
}

p {
  background-color: blue;
}

Paragraphs will be blue. Another example:

body p {
  background-color: red;
}

p {
  background-color: blue;
}

Paragraphs will be red since "body p" is more specific.

Edit: Also try to avoid using !important. It is supported but a side effect is that you can never override it (ever). Thus only use it in the really extreme cases where you have no way of knowing how to construct specific enough rules (e.g.: generic print.css).