Jamison Dance
Jamison Dance

Reputation: 20184

How do I prevent my style from being overridden another style on a surrounding div?

It seems elementary, but here is problem.

Stylesheet like so:

#Content h1, #Content h2, #Content h3, #Content h4, #Content h5, #Content h6 {
  color: #405679;
}

h3#issueHeader {
  color: blue;
}

HTML like so:

<div id="Content">
  <h3 id="issueHeader">In This Issue:</h3>
</div>

Instead of my issueHeader selector overriding the Content selector like I would expect, Firebug and my eyeballs show me that the color is inherited from the div, and the issueHeader selector is overridden. Hunh?

Upvotes: 36

Views: 83113

Answers (6)

dnagirl
dnagirl

Reputation: 20456

CSS gives more weight to styles with more specific selectors. So if you want #Content h3 not to override h3#issueHeader, give it another selector: e.g. #Content h3#issueHeader

If your h1...hx elements are meant to be generally #405679, set them to that without the #Content selector. Then override them with a more specific selector when you need to.

However, because the way weight is calculated, we need to use closest element/class in our selector to get enough-weight, for example:

  • Consider we want to style "z" element.
  • But our style is overridden by "y z" selector (without quotes).
  • Even if our selector is more specific:
    • Starting from "a b c" all the way to "u v w" (without x).
    • We can't get more wight than "y z".
    • But "x y z" selector will have enough weight (as x-tagged-element is parent of y-tagged-element).

Upvotes: 44

nadhem
nadhem

Reputation: 188

You can use the Shadow DOM which will add a complete encapsulation to your element and then it will not be affected by any global styles. You can find more about that in this article : https://bitsofco.de/what-is-the-shadow-dom/

Upvotes: 1

Gavin Miller
Gavin Miller

Reputation: 43815

You can throw the !important attribute on h3#issueHeader to force the browser to use that style

h3#issueHeader {
  color: blue !important;
}

However, it is only partially supported in IE6


Additionally, this should only be used as a last resort to the other solutions purposed. This is because if users of your website want to override your style, important becomes a useful tool for that.

Upvotes: 55

easement
easement

Reputation: 6139

You are having what's called CSS specificity. Here's a good writup (using starwars to boot), that explains the basics in terms of points and how to calculate what will cascade:

http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

Upvotes: 1

Vian Esterhuizen
Vian Esterhuizen

Reputation: 3904

If id="issueHeader" is duplicated that could do it.

Upvotes: 1

Zack Marrapese
Zack Marrapese

Reputation: 12080

Try setting the selector as:

#Content h3#issueHeader {
    color: blue;
}

This should fix it.

Upvotes: 4

Related Questions