CSS Nesting

The last post I wrote in this section was about choosing between classes and ID’s, while it is important to select the right one while coding, it is very easy to think that to style something you must use a class or an ID. However if you plan a website carefully there shouldn’t be that many within the code. This is because you can nest selectors within one another to create different styles without needing to overuse classes or IDs

The best way to explain this is with an example:

<div id="content">
<p> this is some text  <span class="green">changing to green</span><span class="yellow"> then to yellow </span><span class="green">then back to green</span> and then back to normal</p>
</div>

As you can see in the html above, the text within the paragraph changes between 3 different colours and to do so it is using classes to dictate when this should happen. However the above code doesn’t actually need any classes at all, as it could all be done with nesting like so:

CSS:

#content p { color:#0000FF}
#content p span { color:#00FF00;}
#content p span span { color:#FFFF00}

What the above css is saying is that:
a normal paragraph element within the content ID should be blue,
a span within a paragraph element within the content ID should be green
a span within a span within a paragraph element within the content ID should be yellow

HTML:

With this styling in place the structure of the html would then look like this instead of what was shown above

<div id="content">
<p> this is some text <span>changing to green<span>and then to yellow </span> then back to green</span>then back to normal</p>
</div>

As the css above has been created to change the colour of a span is within a span, the above html reflects this by opening the yellow spanning text within the green spanning text.

So there you have it nesting selectors within other selectors, so next time you are wondering if you should use an ID or a Class for styling an element, maybe its worth seeing if you can use what you already have and style without either of them

2
Comments

  • Ron
    March 18, 2012 | Permalink |

    Hi,

    Wanted to take a minute and thank you for your work. I’ve been using CSS and HTML for some time and often need to find explanations of bits and pieces of both. Your clear and concise explanations and definitions are, for me, brilliant.

  • Helen
    March 21, 2012 | Permalink |

    Thank you for the kind comment, I’m really glad that you’ve found my blog useful :)

Have Your Say

Your email is never shared. Required fields are marked *
To add code to a comment use this [code] your code here [/code]