Forum Moderators: not2easy

Message Too Old, No Replies

Why is my class not working?

         

Gibble

7:23 am on Dec 12, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Why are my styles not applying as I think they should be?

Here's the relevant code


<style>
#content h1, h1 {
padding-left: 20px;
background-image: url('../bullet.png');
background-position: left;
background-repeat: no-repeat;

}

.nobullet {
background-image: none;
}
</style>

<div id="content">
<h1>in div</h1>
<h1>in div</h1>
<h1 class="nobullet">in div</h1>
<h1>in div</h1>
</div>

<h1>out of div</h1>
<h1>out of div</h1>
<h1 class="nobullet">out of div</h1>
<h1>out of div</h1>

Even more peculiar, if I add different background-colors, I get a completely different behavior...

...anybody have any insight as to why this is happening?

I'd rather not have to hardcode styles into those places I don't want a bullet inserted.

Thanks,
-C

SuzyUK

9:44 am on Dec 12, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi Gibble,,

you don't quite say how you're expecting them to be, but I presume the "nobullet" class is working outside the div but not inside

the reason is CSS Specificty [google.com]

#content h1, h1
and
.nobullet
ALL apply to the h1 with the class of .nobullet inside the div - you might think that .nobullet should get preference because of the Order of The Cascade [w3.org].. but NO

#content h1 is overruling .nobullet because it is more specific - see Calculating a selector's specificity [w3.org]

#content h1 contains an ID attribute selector as well as an element selector so points 'b' and 'd' apply giving it a specificity of [0,1,0,1]

.nobullet only contains a class attribute selector so point 'c' applies giving it a specificity of [0,0,1,0]

the specificity ranking is read that a beats b beats c beats d so 'content #h1' applies regardless..

you can fix it by adding an ID attribute selector to the .nobullet rule :

#content .nobullet [spec: 0, 1, 1, 0]
or
#content h1.nobullet [spec: 0, 1, 1 ,1]

Tip: once you start using ID attribute selectors in the CSS, you need to keep using them to ensure Cascade applies ;)

hth
Suzy

Gibble

5:27 pm on Dec 12, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Suzy,

Yep, that's exactly what the problem was. I did think it should have worked because of the order of the cascade.

Thanks! It's working perfectly now.

Though, I would have thought, that using a class attribute would have overridden any included style sheet styles...since, in my mind, placing a class on a tag, is more specific, than the tag itself.

Ah well. You learn something new each day.

Thanks again,
-C