Skip to main content

6 steps to writing better CSS

Write better CSS
(Image credit: Envato/Future)

We've all been there. As you slowly open up the styles.css file of your latest CSS spectacular, you see that it’s 2,000 lines long and the class you need to change is smack in the middle.

You’re alone, scared and have no idea if it’s okay to edit that class because it could topple something on a completely different page. As a last resort you go to the end of the file and create a new class to tack onto the element that already has seven other classes on it. This is a common experience for any developer who’s been working with CSS long enough (see our favourite examples of CSS animation for some CSS inspiration).

So, let’s talk about what the goal should be when writing good CSS. The goal isn’t to create clever and complex rules. It’s not to engineer a selector string so that it’s as broadly applicable as possible. The goal of good CSS should be to write simple, modular and, most importantly, easily maintainable rules. Here we give you some simple and smart rules to help you create and maintain a healthy codebase. 

If you're after more web design advice, don't miss our pages on website layout,  web hosting services and the best web design tools around. Got a new site on the horizon but don't want to code? Choose the perfect website builder.

01. Add order and structure to files

Write better CSS - Folder structure

Structure files by page for quicker and easier access (Image credit: Kyle Trenal)

First, consider breaking up styles into their own CSS files based on an agreed upon structure between developers and then stick to it. Opening a poorly organised styles folder is a horrible experience. You have no idea what styles are in which files and how changing one style will affect another. Remember that your server couldn’t care less if you gave every single style its own file and then linked them all or minified them into one at the end. 

Your site would load very slowly but the server would handle reading them just fine. File structure is for humans only and if your file structure isn’t providing any value then it should be rethought.

One of the least confusing ways to structure files is by page. If you're working on an about page and something needs fixing, you go to the about.css file. This avoids the issue of affecting styles outside the about.css. Then all you need to do is check for changes in the about.css file.

This doesn’t fix the problem of file length though. A significantly long page might easily have over 1,000 lines of CSS. Structuring your files internally is a way to mitigate this. Sorting alphabetically inside a file means if you are searching for something beginning with C and it's not there, then you know it's not included. 

This also works for styles that already exist. By grouping everything alphabetically you can see if a style has been written three or four times throughout a file.

        padding: 1rem;
/* .contactHeader would go here if it existed
 Since it doesn’t we can safely assume it doesn’t exist */
        padding: 10px 5px;
        background: #ccc;

02. Build a base CSS file

Not all styles will belong to only a single page and it’s common to have styles that exist on multiple pages. It’s also common to have styles that apply to the business overall and not just the website. This is where you will write very general styles that don’t really belong to anything. For example the different colours you’ll use, fonts, typography, as well as any resets that are specific to your site. 

You may also want to include basic component-like styles in this section, such as buttons, form elements and alert styles. Think of this section as the style guide for your site. Not only will this give your site an easier way to maintain CSS, it will also ensure that styles are applied uniformly. 

This is a place where you may want to include styles that belong to sections of the site that repeat themselves on multiple pages, such as a header or a footer. If you have a significant amount of styles in these sections, it can help to break them out into their own files such as header.css and footer.css.

Just be careful that you don’t start including styles in those files that don’t actually belong. Remember a messy folder structure is a great way to make maintaining CSS difficult. 

03. Separate your layout from other CSS

Separate layout styles to make it easier to focus on other CSS (Image credit: Kyle Tranel)

Those of you familiar with SMACSS may be familiar with the idea that layout styles can be separated from the more general styles you’ll apply to your site. By separating these styles from the rest of your CSS, it means you can more easily focus on how different sections should look and less on how they should behave relative to sections close to them.

This can be accomplished by adding a grid system such as the popular Bootstrap library or by implementing one yourself. It’s a good idea to speak with the designer of the site at this point, as many designers will use a grid system when they’re creating a site and you’ll want to get as close to that as possible.

04. Write your CSS modularly

Creating modular CSS is about identifying when something belongs to a group (Image credit: Kyle Tranel)

Separating your layout CSS reveals another way of simplifying your CSS. There are many different methodologies related to CSS. There’s SMACSS, BEM, OOCSS to name a few but whether you’re calling them sections, parts, modules, components or blocks they all have one thing in common. That is they attempt to add reusable and specialised parts to your style sheet.

In doing so we keep our styles as DRY (don’t repeat yourself) as possible and create encapsulation. Side effects in CSS are a big deal. The browser applies CSS in a true or false manner: if a style matches it’s applied, if not then it’s skipped. This allows for a style that wasn’t meant to be applied by the writer to still match and change how a page looks. When we write CSS more modularly, we reduce these side effects by encapsulating the styles. 

A component or module is a section of HTML that is grouped together and whose styles affect each other. Creating modular CSS is all about identifying when something belongs to a group and then separating it from its surroundings. It means that there is no need to worry about the outside and likely don’t need to worry about any modules inside it as well. 

We may write the classes that create this as follows:


What actually goes in these styles is unimportant but what it does do is allow for control of what happens in the whole header, the top line of the header and the bottom line. By namespacing them with the .aboutHeader class ensures that no other styles will be applied to them.

<div class=”aboutHeader”>
        <div class=”aboutHeader_topMenu”>
        <div class=”aboutHeader_bottomMenu”>

05. Avoid long selector chains

When you write components it’s easy to keep them relatively shallow, going no more than two to three layers deep in class selectors. However, some components may have you reaching five, six or even more layers down before reaching the element you wish to target.

Remember that CSS does not have the ability to abstract problems away like JavaScript; it has no control flow or functional ability. That’s a good thing though, so don’t try to mimic it by creating long selector chains, deeply nested styles or highly generalised styles.

Here's an example of how not to do it:

.homeCTA .titleContainer .title .subheader .list{}

Here's how you should write it:

Rename subheader classes to be their own component

.subheaderCTA .list{}

A selector chain like the 'how not to do it' example above indicates you’re targeting the wrong style. It’s not often a chain like that is actually necessary. Instead it likely means you have a component inside of a component and that you should target it directly. Modular CSS encapsulation breaks down if you try to encapsulate too much inside of it, meaning you’ll start seeing side effects again.

06. Don't forget your principles

There are many ways to create CSS and each project you work on will be slightly different. Although it’s almost inevitable that any codebase will eventually need an overhaul, you can use these principles in order to slow that from happening. And if you're working as part of a team, make sure you keep your design files in secure cloud storage, which can be accessed by everyone.

At all times you should be focusing on making sure your styles are dry, encapsulated, readable and searchable. Initiating the principles discussed will help make sure things can be more easily maintained and changed in the future. 

So remember to keep some order to your file system and your files. Namespace and modularise your styles. Separate basic styles, layout styles and general styles to keep separate concerns. 

Finally, keep your styles as simple and shallow as possible. The first time you write a new style it shouldn’t be difficult and, if you find it is, consider whether you’re making that section too complicated. Because if it’s hard the first time, just imagine what a headache revisions will be.

This article was originally published in issue 323 of net, the world's best-selling magazine for web designers and developers. Buy issue 323 or subscribe to net today.

Read more: