A seemingly simple language yet a tangled mess of complexity. If you are picturing a giant CSS file from your website, you are on the right track. Yes, CSS can start out as a really simple language to learn but can be hard to master. The CSS chaos starts slowly and seems innocuous at first. Overtime as you accumulate features and more variations on your website, you see the CSS explode and you are soon fighting with the spaghetti monster.
Luckily this complexity can be brought under control. By following a few simple rules, you can bring order and structure to your growing pile of CSS rules.
These rules, as laid down by Scalable Modular Architecture for CSS (SMACSS), have a guiding philosophy:
The above principles can be translated in the following ways:
header
, footer
, navigation
, sidebar
, content
. This can go as deep as you wish. For example, the content
area will be broken down further on most websites. When defining a layout rule make sure you don’t mix presentation rules such as fonts, colors, backgrounds or borders. Layout rules should only contain box-model properties like margins, padding, positioning, width, height, etc.,Naming conventions such as below make it easier to identify the type of rule: layout, module, sub-module or state
.l-*
.is-*
.<name>
.<name> .<name>-<state>
Alright, there are lot of abstract ideas in here. Let’s do something concrete and build a simple webpage that needs to show a bunch of contact cards, like below:
There are few things to note here:
card
, pic
, company-info
and contact-info
card
module has a sub-module: card-gov
, for contacts who work for the governmentcard
and contact-info
module change layouts via media queries./* ----- Picture ----- */
.pic {
}
.pic-right {
}
/* ----- Card ----- */
.card {
}
@media screen and (max-width: 640px) {
.card {
}
}
.card h4 {
}
.card-gov {
}
.card-gov .contact-info {
}
/* ----- Company Info ----- */
.company-info {
}
.company-info-title {
}
.company-info-name {
}
/* ----- Contact Info ----- */
.contact-info {
}
@media screen and (max-width: 640px) {
.contact-info {
}
}
.contact-info-field {
}
.contact-info-field:after {
}
To me the whole idea of SMACSS seems like an application of some of the ideas from OO languages. Here is a quick comparison:
SMACSS can save you a lot of maintenance headache by following few simple rules. It may seem a little alien at first but after you do a simple project, it will become more natural. In the end, its all about increasing productivity and having a worry-free sleep ;-)
Some resources to learn more about SMACSS: