1

Somehow the descendant selector overrides my .red_p class. How do I avoid that? I don't want to set a class for each p element.

HTML:

<html>
  <head>
    <style>
      .red_p {
        color: red;
      }

      #main p {
        color: blue;
      }
    </style>
  </head>
  <body>    
    <div id="main">
      <p>This should be blue.</p>           
      <p class="red_p">This should be red, but is blue.</p>             
    </div>  
  </body>
</html>
nQk
  • 105
  • 1
  • 5
  • `!important` ? :) Yes, CSS is sometimes a pain in the *** – Roko C. Buljan Jun 09 '14 at 22:33
  • Because an `id`-selector is more specific than a class-selector, and a longer selector is presumed to be more specific/accurate. Remove `#main` from your second selector, and it should work fine. You may also want to read: [CSS selectors - Points in CSS Specificity](http://stackoverflow.com/questions/2809024/points-in-css-specificity) (here on SO). – David says reinstate Monica Jun 09 '14 at 22:33

2 Answers2

1

Increase the specificity of blue. For the current code, #main p is much more specific than .red_p because it contains an id.

You can include an id in the red rule like .red_p, #main .red_p and move it after the blue rule (latter styles override earlier ones) or use !important.

Specificity works like this:

  • If A is !important and B isn't, A is more specific than B. Halt.
  • If A has more id selectors, A is more specific than B. Halt.
  • If A is an inline style and B isn't, A is more specific than B. Halt.
  • If A has more class selectors plus pseudo-class selectors plus attribute selectors than B, A is more specific than B. Halt.
  • If A has more elements than B, A is more specific than B. Halt.
  • If A is declared after B, A is more specific than B. Halt.

(The universal selector does not affect specificity)

http://cssspecificity.com has great examples and pictures.

bjb568
  • 9,826
  • 11
  • 45
  • 66
0

In CSS, there are rules for specificity (quoted from MDN, and examples added to be clearer):

The following list of selectors is by increasing specificity:

  • Universal selectors - ex: *
  • Type selectors - ex: p
  • Class selectors - ex: .p_red
  • Attributes selectors - ex: [class="red"]
  • Pseudo-classes - ex: :hover
  • ID selectors - ex: #main
  • Inline style - ex: style attribute in your HTML

So, you can add specificity to your selector. There are, in your case, several ways to do this :

#main .red_p
#main p.red_p

Or, third way, remove the #main in #main p, so it'll be less specific than your red p rule.

Bigood
  • 9,457
  • 3
  • 36
  • 65