views:

33

answers:

2

Hi there, I've been making websites for years and theres on thing that really bugs me and confuses me.

I set a link style in the css file for a content div in my website and this successfully styles the links.

However if i create a span or div inside this div with a new link style i end up having to add in !important to various attributes which i can only tell by trial and error.

Is there any way around this or am I doing something wrong?

Thanks

+2  A: 

My intuition is that you're having problems with your selector specificity.

Ensure that your new link selectors have a higher specificity than the ones in the enclosing element. Normally this would mean using a selector like div.outerdiv div.innerdiv a.class rather than just a.class etc.

For example:

<div class="outer">
   <a class="outerlink" href="#">Outer Link</a>
   <div class="inner">
      <a class="innerlink" href="#">Inner Link</a>
   </div>
</div>

If you use these selectors you may have trouble (depending on css ordering etc.):

a.outerlink { **css here** }
a.innerlink { **css here** }

Even if you use these selectors, it's not guaranteed to work how you want:

.outer a.outerlink {}
.inner a.innerlink {}

However, these selectors should work best, ensuring your innerlinks override attributes:

.outer a.outerlink {}
.outer .inner a.innerlink {}

Make sure you specify all the attributes you want to override in the .innerlink css.

Once you understand specificity, the power of the darkside will be yours.

ghoppe
Thanks very much :) - that clears it up - I was half doing this and not all the time.
Stefan
A: 

I think I know what you are referring to, and I solve this problem by adding "a" after the inside span or div css rule. Let's assume you have a general rule:

a
{
    color:white;
}

If you want to override this rule in a div, you have to write

div a
{
    color:yellow;
}

and not just

div
{
    color:yellow;
}

This is because the link is inside the div, so the first rule is stronger than the third for links.

greg0ire