pitosalas
pitosalas

Reputation: 10862

CSS class priority

I think I understand class specificity rules. I would like to have a class or id called themecolor that I can put on any element that I want to take on that color. Sometimes it's a background, other times it's the color of an icon.

.themecolor {
  color: rgb(47, 86, 111);
}

I am using it with Bootstrap so for example I have this:

<div class="themecolor navbar navbar-inverse navbar-fixed-top">

and this:

<span class="glyphicon glyphicon-#{icon} themecolor" data-toggle="tooltip" data-placement="top" title="#{tooltip}"></span>)

It doesn't work because there are more specific rules in each of those cases which defeat my color. However I'd rather avoid having the theme color rule be dependent on where it's used.

By the way I tried !important and that didn't do it either.

Upvotes: 0

Views: 1291

Answers (2)

Rounin
Rounin

Reputation: 29463

CSS is all about context.

The style an element receives depends on:

  1. Specificity
  2. Position in the cascade

Specificity

  • p {} is less specific than
  • p.introduction {} which is less specific than
  • article p.introduction {} which is less specific than
  • article#profile p.introduction {} etc.

Cascade

For situations where specificity is equivalent...

  • In article p {color: green;} body p {color: red;} the paragraph text will be red.

  • But in body p {color: red;} article p {color: green;} the paragraph text will be green.


So, although you write:

I would like to have a class [...] called .themecolor that I can put on any element that I want to take on that background-color.

as you will have seen, using:

.themecolor {
background-color: rgb(47, 86, 111);
}

will often not work - because, your .themecolor declaration might easily (albeit accidentally) get overridden by a more specific selector elsewhere in your stylesheet, or by a selector of equivalent specificity further down the cascade.

Better then, to group selectors together, using your .themecolor as a quasi-variable:

.THEMECOLOR,
.navbar.themecolor,
.glyphicon.themecolor {
background-color: rgb(47, 86, 111);
}

You will then be able to add as many new elements to this list as you wish, always stating the main Bootstrap class of the element immediately followed by .themecolor:

.THEMECOLOR,
.class1.themecolor,
.class2.themecolor,
.class3.themecolor,
.class4.themecolor,
.class5.themecolor,
.class6.themecolor {
background-color: rgb(47, 86, 111);
}

N.B. The syntax .class1.themecolor means:

When an element has .class1 and it has .themecolor

Upvotes: 1

pitosalas
pitosalas

Reputation: 10862

I messed up: @Paulie_D correctly reminded me that I was using "color" on a navbar, where I meant background color.

I am still curious about my question though

Upvotes: 0

Related Questions