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!)