CSS Best Practices

Let the browser do the work

If you build your websites with correct semantics, most basic styling will be done for you. Headings will look like headings, paragraphs will look like paragraphs, lists like lists.Doing a job that is half finished is way easier than starting from scratch, right?

This plus a really basic normalize/reset[1] (nothing much!) will take you super far.

Move styles as high as you can in the DOM

Sort of an extension of the last point. Instead of manually applying spacing to each element, use the "lobotomized owl"[2] selector to add margin to those inside a container. Instead of setting font sizes by pixel size, use rem and a ratio[3] to respect user's customizations and let math handle the designs. Instead of styling one form, style all forms.

Not only does this make your life easier, it also brings cohesion to your website.

Don't try to use a screw as a nail

If you can't get the design quite right, it's probably better to go back to the drawing board. Just because you can, doesn't mean you necessarily should. Oblique strategies comes to mind. How else can you represent this? Does it need to be this specific way? Can we get rid of it?

Use BEM[5]

Using a structure like this (along with some other kind of abstraction, like Sass[6] and their 7-1 pattern[7]) makes CSS maintenance much more straightforward. Not all projects require all of this, but even starting with a simplified version allows you to not have one sprawling CSS tome, but instead encapsulated ideas that cascade naturally.

Don't make CSS do content or anything functional

CSS is styling. Don't make it add content onto elements using ::after, don't use it as a cheap pagination tool or tab system. HTML is for content; CSS is for styles; Javascript is for functionality. Think progressive enhancement. If you lose your JS, your styling shouldn't suffer. If you lose your CSS, your content shouldn't suffer.

References

  1. A Modern CSS Reset
  2. Margins Considered Harmful
  3. TypeScale
  4. Classless CSS
  5. Block, Element Modifier
  6. Sass
  7. 7-1 pattern

Last modified: 202408160316