Zachary Wright
Zachary Wright

Reputation: 24070

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?

Upvotes: 9

Views: 39572

Answers (5)

suketup
suketup

Reputation: 469

The !important rule overrides a particular property in css.

So in case of overriding a property you should always use it with the value.

More details on: https://css-tricks.com/when-using-important-is-the-right-choice/

Upvotes: 1

Robert
Robert

Reputation: 21388

There are a couple ways, you can use !important at the end of the declaration as such:

.red {
    background-color: red !important;
}

Also, the more specific a declaration, the more prevalent it will be. So anything in table.myTable td.red {} will have more prevalence over anything in td.red{}.

Upvotes: 8

ipartola
ipartola

Reputation: 1646

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).

Upvotes: 16

M4N
M4N

Reputation: 96596

This is all a question of the specificity of the css selectors used (i.e. how exactly does a selector match any given HTML element). The more specific a selector is, the higher the priority of its styles are.

For an in-depth explanation of CSS selector specificity, have a look at this page: CSS Specificity: Things You Should Know.

Upvotes: 4

Nikita Rybak
Nikita Rybak

Reputation: 68026

There's a standard way to give some style priority.

td.red { background-color: red !important; }

Upvotes: 2

Related Questions