Override a css heading with a new style class

antmw1361 picture antmw1361 · Jan 4, 2013 · Viewed 15.4k times · Source

I am using one of the free web design templates to create my own site. The template uses a css style sheet and defines lots of different styles with similar names. I defined some new styles, but the problem is new styles do not effect to my pages. For example, this is the style for heading2 in one of the blocks:

 #body .article h2 {
color: #ffaf04;
font-family: Georgia, serif;
font-size: 36px;
font-weight: normal;
letter-spacing: 2px;
line-height: 48px;
margin: 0;
padding: 0 48px;
text-align: center;
    }

I try to add and use this style

 .eventTitle { font-size:28px; color:black  }

but when I use

 <h2 class="eventTitle">something</h2>

style from #body .article is applied not eventTitle.

I was wondering maybe there is some parenting or protecting of some parent styles in CSS, or maybe some div items has to use some specific class styles or something.

I appreciate all comment and ideas in advance.

Answer

chharvey picture chharvey · Jan 4, 2013

Your second selector is less specific than the first selector, so even if the second one comes after the first one in your CSS file, the first one will be applied.

Read more about specificity here (a blog post written by Chris Coyier) and here (the W3C specs).

Here is a very funny comic that pretty much sums up the concept of specificity.

My suggestion: Try taking out #body in the first selector (unless there's a very good reason it is there in the first place). Then try changing your second selector to

.article .eventTitle { font-size:28px; color:black  }

I would not recommend adding the !important modifier to your css commands. It should be used sparingly (as @Cody Guldner states). Really, your CSS should be clean and concise. Using !important a lot is only setting yourself up for more work in the future. Personally, I only use it for bug fixes and experiments.