CSS Design Patterns
CSS Design Patterns can to help you make sense of using stylesheets and writing CSS code. It’s easier to write CSS when you use a set of guidelines describing how to write your code.
As mentioned in What is CSS?, CSS is globally scoped, that’s the entire point of cascading, and only through careful planning can we restrict the scope of the styles. Writing CSS is an exercise in cascade management. As a developer, when we code pages, we want the CSS to only be applied where we want it, and nowhere else. Various design patterns (theories about how to write CSS) were developed to make it easier.
One attempt to do that was name-spacing. Every one of your selectors would start, usually made up of 2-3 characters, with a code disignating the unique name-space of that selector. The name space for an art site might be .art
. My personal site might be .lly
. For small sites it usually isn’t an issue. Name-spacing usually comes into play with large organizations that share code.
A deeper attempt at localizing CSS was the media object:
Common CSS Design Patterns
CSS Design Patterns are ways to structure your CSS so that it’s easy to write and easy to update when you need to make changes. A design pattern is just the method in which you write your code so that it’s easier to understand.
You make end up using one of these, or, you may use slight variations.
OOCSS
OOCSS Object Oriented CSS helped to deliver the Media Object. The focus of OOCSS is the idea of treating page elements as objects, giving all these objects classes, treating objects’ classes as single entities in style sheets, and taking it from there
BEM
BEM Block Element Modifier
SMACSS
SMACSS Scalable and Modular Architecture for CSS
Atomic CSS
Atomic CSS, sometimes referred to as Functional CSS, is the approach to CSS architecture that favors small, single-purpose classes with names based on visual function.
Atomic CSS is the extreme attempt at localizing CSS. Each class would contain only one property. It’s the exact opposite of cascade.
.bg-blue { background-color: #00f; }
.p2 { padding: 2px; }
.p4 { padding: 4px; }
.p8 { padding: 8px; }
My personal feelings about Atomic CSS is that it’s inline styles with extra steps. It also usually requires more setup (toolchain, CSS post-processing, etc.) than I would be comfortable with recommending, for setting up a hobby site.
Exercises
- Write a “card” component using each of the design patterns.