Web Development

Decendent ID selectors

Posted on: March 30, 2008

Recently I had submitted my CSS for a review. One of the feedback suggested that I get rid of multiple ID attributes in a rule. I had several selectors as below in my CSS.

#grandparent #parent #child{/* property values */}

Since IDs are unique in a document it makes little sense to use ID attributes in a descendant selector. Well, sounds true. When something is unique why would you need to qualify it with something else. I was wondering why would the CSS specification asks to add up the number of id attributes to decide the specificity of a rule.There is one use that I can think of. Consider an application wherein you serve a default theme to the user (Not necessarily an end-user. Could be some other application). The user can customize your default theme. And to add to it the customization should be source order agnostic, it takes precedence irrespective of whether it appears before or after the default theme.One strategy to achieve this is to design your default theme with moderate specificity. For e.g.

#child{}

Now the user can add more id attributes to the rule to increase the precedence of the custom stylesheet. 

#parent #child{}

Above rule takes precedence irrespective of whether it is above or below the default stylesheet.Well, this could be achieved in different ways. We can increase specificity in several ways but this seems to be the safest/surest way (barring ‘style’ and ‘!important’) for such scenarios mainly because id attribute values are unique. So the users can override the rule more precisely without side-effects. 

Advertisements
Tags:

1 Response to "Decendent ID selectors"

Your indeed right with this piece!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: