4 Tips for Writing Cleaner CSS

Daniel Cook
2 min readApr 9, 2020
Photo by Pankaj Patel on Unsplash

Styling can be difficult to maintain, particularly if you are working with pure CSS. But why would you be writing pure CSS nowadays when LESS and SASS exist?

Well maybe for the following reasons:

  1. You might be learning web development.
  2. You might be working on a simple project and trying to keep things minimal.
  3. You might like reminding yourself how to work independent of tools such as those.

Here are a few tips when working with CSS to keep it clean, maintainable and efficient.

Avoid complex rules

Complex rules have a performance hit as the browser has to think harder when evaluating them. Instead of you saying all buttons are red, you are saying all buttons, inside a form, inside this container, inside the main tag, inside the body tag are red. The browser needs to think if this is true, and that comes at a cost. Instead try to use classes that are not too generic and that are not likely to cause issues regarding unwanted styling changes on other areas of the site.

Put the rules relating to the top of the page at the top of the file

This is a bit of an odd one but it really helps. Think of your CSS file as describing the page styling and try to keep it so that styling that affects certain areas of the site is placed within a similar position in the CSS file. So footer styling will be at the bottom of the file, header and the top and page content styles somewhere in the middle.

Do not repeat yourself

This is a common principle in coding but it applies to CSS as well. Let’s say you have 5 different types of button your site. Try to have a generic class that is shared between them all instead of repeating styling for each. For example you might have .btn (common button styles) and then .btn-primary for your primary button specific styles etc. This will help with maintainability as if you want to change a style across all buttons it can be done in one place.

Group styling by components and by page

You don’t want to be hunting around in your style files trying to find that next button class. Group things together in a logical manner so that things are easy to find. Button classes in one place, form styling in another. Similarly page specific styling (if it has to be done) should be grouped by page. Add comments to make it clear what is what.

--

--