How not to get angry with CSS

... opening ...

Rule 0: Styles work opt-in, not opt-out

The problems of CSS can fall into many categories, but the most notorious one in my book is styles affecting things they weren't meant to affect. Examples:

  • I defined a default button style, now I want to use bootstrap but cannot

Organise your styles into small modules

.....Make your modules....

I like to compare CSS modules to import statements in Python. If I do import myapp.blogposts, I can now use the functionality from "blogposts" module, but the import itself doesn't cause any visible effects. Similarly, including myapp/blogposts.css on my page should load the corresponding styles and make them available to me, but shouldn't itself affect how the page looks.

The library actually starts doing its things if I fire a myapp.blogposts.get_last(). Similarly, the CSS module should only do something when I use a class name that is defined in it.

Whenever you define a CSS module that doesn't obey these rules, you put a pair of handcuffs on yourself. Imagine situations like "augh, I just want to put on my page but once I include the styles for it, everything else will suddenly break because one of its dependencies also redefines paragraph spacing".

There should be very few exceptions from this, here are my picks:

  • global reset - normalize.css is the go-to choice nowadays, a safe approach of evening out browser differences while keeping basic HTML conventions in place
  • box-sizing: border-box globally is also handy (and just plain logical), many third-party components like Semantic UI go as far as to actually depend on this being a global

Page defaults can go to modules too

I'm sure you want

Modules should be tiny

Modules don't need to know about your data

You shouldn't be re-using same class names for behaviour and appearance


Comments powered by Disqus