Jump to content
Stef's Coding Community
Sign in to follow this  
j22cal

css specificity advice?

Recommended Posts

I have been trying to come up with a good practice for css specificity. I understand how it works, I just tend to over use specificity and wondered what you do. I will provide some examples of what I am referring to below:

 

 

Here is one of my more specific examples:

 

#main .content .inner {
... styles ...
}
   #main .content .inner p {
     ... styles ....
   }

 

In some of my other styles, I started by being specific and then dropping the specificity by a level for each style. Like:

#main .content .inner {
... styles ...
}
   .content .inner p {
     ... styles ....
   }
      .inner p.large {
         ... styles ...
       }

 

How specific are you with your styles?

 

Thanks! :)

Share this post


Link to post
Share on other sites

I use hardly any specificity, just the basic class .inner or id #content, but that's because my sites usually have the same structure and styling on every page.

 

On a really large site where there are different structures or styling to different sections of the site you probably would need to use specificity to identify the page type (or use a different stylesheet for the different page styles).

Share this post


Link to post
Share on other sites

It's basically considered quite inefficient to use elements for styling, using selectors such as:

 

.inner p {}

.inner a {}

 

etc.

 

As the browsers work from right to left, so they start by taking all the P tags or A tags then for each one it looks for a parent with class .inner

 

It's considered best practice to put a specific class on those P and A tags (just as an example, it can be div or dd or dt or whatever) and not use any selectors with descendants. Basically if there's no style that are conflicting with your current CSS statement, then you don't really need to be so specific. Instead of #main .content .inner u can just do #main .inner

 

If there's nothing between .content and .inner then you don't need to write .content .inner p you can just do straight away .content p which will be more efficient.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...