Every h2 except those who don't have a class?

I am wondering how I can apply a style to EVERY h2 that TO ANY class is attached to it, thus having the effect that the style will NOT be applied to simple h2..eg ..

<h2 class="1"></h2> <h2 class="2"></h2> <h2 class="3"></h2> <h2 class="a"></h2> <h2></h2> 

All those with a class should have a style - and just h2 shouldn't (This is a huge site with hundreds of styles) ... so is there any easy way to do this?

+4
source share
3 answers

There is a way to do this, but this is only possible with browsers that support CSS3: not a pseudo-class.

 h2[class] { /* Styles for <h2> with a class, regardless of the value */ } h2:not([class]) { /* Styles for <h2> without classes */ } 

Hope it works!

[Edit] I made a simple demo for you - http://jsfiddle.net/fL2sT/

+5
source

What you are asking for is how CSS works by default.

The right way to style elements that don’t have a specific class assigned to them is the style of the base element, as Asshan showed above. I do not know why he got down.

 h2 { property: value; } 

Note that if H2 elements have classes assigned to them, then this style can override your base style.

So, if you have: h2 { color:#333; font-size:2em; } h2 { color:#333; font-size:2em; } h2 { color:#333; font-size:2em; } as the base style, and then apply class="myClass" , where: .class { color: #000; } .class { color: #000; } , then the color of the base style will be overridden (but not the font size). This is a cascade in cascading style sheets.

Another way is to conditionally configure them:

 div#nav h2:first-child { property:value; } 

which gives you contextual control, but again, the purpose of the class will always override the base style and can also override contextual targeting if the class application has a higher specificity.

+3
source

Why not just use

 h2[class] { ... } 
+2
source

All Articles