Tuesday 10 July 2012

CSS: grouping and nesting

   


One of the basic things to know about CSS is how to select elements in a page. However, not many of us know how to do it efficiently.
In this short post, we are going to see how to group and nest CSS selectors.

General idea
When we re working with big stylesheets, we often end up trying to understand what we have written. That's quite common if we do not follow best practise rules while developing a web site. I've already stressed out that idea, however I believe I should repeat myself: keep things tidy.
Ok. That's the general idea. Now let's move on.

Grouping
If we want to apply the same declaration to different selectors, we might end up having something like:
p {
   color: #000000;
}
div {
   color: #000000;
}
.specSel {
   color: #000000;
}
In the above example everything might look simple. We definitely need to group those rules!
Sometimes things are much more complicated, because the above rules are scattered all over our stylesheet and so it is more difficult to spot them. In those situation we might benefit from a tool like HTML compressor, but that's another story...
Now, let's see how to group the above rules:
p, div, .specSel {
   color: #000000;
}
And that's it!
Again, the problem is not "doing it", but finding where to group the rules, and how.
We might have different selectors with just one declaration in common. In that case, we group the common declaration and leave the rest separated.

Nesting
Nesting is different. It is used to select an element which is inside another element.
For example we might have a rule for p:
p {
   color: #FFFFFF;
}
The above rule will apply to all p elements. In some case, we might need to change a specific p element which is inside a div. The rule will be applied to all p tags inside a div tag:
div p {
   color: #000000;
}
Or better, the p tags inside a div with class = "specSel":
.specSel p {
   color: #000000;
}
Isn't it neat?

Ok folks, see you next time (if I don't melt for the hot weather!)

2 comments:

  1. Another great tip is combining classes on elements to save on the amount of CSS you need to write. I've been using CSS for well over 8 years now and I'm always finding more efficient ways of laying out my CSS.
    Eg:

    <\div class="big red">Big and Red
    <\div class="big green">Big and Green
    <\div class="big">Just big

    .big {font-size:20px}
    .red {color:red}
    .green {color:green}

    You can also target just the top element like this:
    .big.red {border:1px solid #000}
    The class names musn't have a space between them and they must be in the same order as the classes on the targeted element.

    ReplyDelete
    Replies
    1. Thanks Reverson. Why don't you write a short post about your 8 years?

      Delete

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.