CSS structure & anti patterns (Part 1)

"CSS is quick to learn, but takes years to master".

- Not sure where I first read this but it's still true today.

It's difficult to give years of experience as training. People expect designers to know things after a day of training that you'd normally learn with months or years of experience. Some patterns I'll talk about in this post only reveal themselves as bad decisions later on. The best I can do is show you mistakes I've made, and other designers have made. Hopefully you can learn from where we went wrong ;).

Anti-patterns.

Anti-patterns explained: What not to do and why.

Found something controversial? Leave me a comment and we can discuss it further :).

1. Avoid separating styles for the same things.

A case of this I've seen before is separating into different device groups, e.g. mobile.css, tablet.css, desktop.css.

Similar used to be done on sites with a ie7.css file etc.

On the face of it, it sounds like a good idea. Everything is separated out, but it's separated in the wrong way and ultimately it's a naive approach. It often encourages duplication because the blocks of style are separated. This makes it difficult to track down specific styles for an element as they then span multiple files, which often ends in code being copied for each file as it's forgotten it's already set and inherited.

Instead my advice is to build specific module css files, we'll come back to how you do this later in the post.

2. Don't copy paste chunks of code.

This one seems obvious when thinking about most coding languages, but maybe not so with your css.

While working on your css, think about how some styles can be joined together. Remember you can join css selectors with commas so code such as:

.banner p {
  margin: 0 0.5em;
  color: #222;
}
.banner h3 {
  margin: 0 0.5em;
  color: #444;
}

Can become this, which is much easier to maintain and keep consistent:

/* ===== Banner module ===== */
.banner h3,
.banner p {
  margin: 0 0.5em;
}
.banner p {
  color: #222;
}
.banner h3 {
  color: #444;
}

Yes the above code is longer but maintainability is what we are aiming for.

3. Avoid naming classes just by their current properties

Such as .red, because what is red? Will it always be red, what if we change to green... Do we go round everywhere changing the class name to green, or do we change the property and will red now mean green.

Ok this one seems obvious especially with my example, but often when designing more modular css you can get carried away and go too abstract to the point of classes for everything like .red, .font-serif, .text-align-right which leads to even worse code.

Instead, try to think of what the element is, such as a block on the sidebar for latest news. you could have a module called .latest-news, but then you could go further and make that a generic .sidebar-block which can be reused for all your sidebar blocks. On top of this you could then still have .latest-news or .sidebar-block-latest-news for specific extra changes on top of the default .sidebar-block, but consider how this could be shared with other blocks on the page too.

4. Don't just slap !important on it ;)

I find !important is very rarely needed, but too often designers try a selector, find it doesn't work and is somewhere overridden. So they give up and slap an !important on it.

Learn about how selectors and inheritance works!

The topic of CSS specificity deserves its own post, luckily there's several out there that do great jobs. Specificity Wars is a fun introduction to it, along with articles on CSS-Tricks, Smashing Magazine and the Mozilla Developer Network

Tools such as Specificity Calculator are also helpful for you to work out why a selector is more specific.

If you don't bother to learn about it, you'll be forever doomed to fight your forest fire of !importants later.

5. Read the source code!

While you're working in systems or you have build scripts that generate a main/master css file from all your other files, don't be afraid to jump in and take a look to work out why an issue is happening or to check your code is being built the way you expect.

Systems sometimes also have to place some css in page, maybe because of their current module architectures, whatever the reason, if that's the system you work within, you'd better be confident you can find where some css comes from. (Luckily dev tools will tell you if css is from a file or on the page). CSS like this deserves care and attention to override. The source code wont lie to you.

6. Dev tools is your best friend, know it inside out!

Better than reading the source code (though that's still important) is using dev tools.

You need to learn dev tools for the browser you're working on. No two ways about it, go learn them now, at least the inspector :).

Here's a link for Chrome and Firefox.

The inspector will save you minutes, hours, days, weeks and more in trial and error.

7. Avoid fixing height & widths when you can.

This often happens when you have a mockup in photoshop and then you try to match the exact dimensions, which is great, except that this likely wont work as the screen size decreases.

Try to make your modules fluid, then they can fit into a grid or take the widths of the container. Patterns like this are core to responsive design.

8. Designing for desktop down or mobile up?

Instead try to think of mobile and up where you can. Often this will lead to simpler css breakpoints and less cruft around content. With this you can think about what's really needed in the design, without too much extra that on mobile wouldn't make sense.

Read more on Mobile First here, or check out Luke Wroblewski's Mobile First book

9. Clearfix the containers of your floats.

The clearfix class is somewhat magical, but really it's very simple. There's a few implimentations of it, but generally the practice involves adding a hidden pseudo element at the bottom of the content that clears the floats.

Sometimes you'll find this called ".clearfix", or ".cf".

Read more about one great example of this here

10. Avoid magic.

Maybe this seems weird when I just said clearfix is magic. But clearfix is simple when you understand how it works. Try to avoid code that seems to magically make things better if you don't understand why. Otherwise, how can you trust it will always work? How do you customize around it without breaking it?

Clearfix is a great example of this as if you did not understand how it works, you may try and add a pseudo element after it in your own css and find the clearfix no longer works.

11. Use the appropriate method for layout.

Often grids or inside blocks instead of floats for layout.

E.g. if you have 3 columns of evenly sized text next to each other, a grid is perfect. If you have a navigation list or boxes next to each other that are sized by their content, normal grids would be a terrible solution. Inline blocks are best for that as they are sized based on the content. If you have a title with a link to the right, float the link to the side, grids again are not really the best for that. There's no one way of doing things right, don't just follow one specific method, think about how it looks and what would really make the most sense. It may take a little longer to stop and think about each part. But if you do it will save you so many headaches later.

12. Don't style every thing as unique.

Try to reuse modules, again this is not to copy and paste, instead create a generic look for basic elements within content, and then create re-usable classes / modules for applying different styles.

13. Opt for relative measurements over fixed when you can.

Simple one, relative measurements such as em, %, rem etc. are more flexible and will often work better with your responsive design than px.

Not that you should cast aside px as a dirty relic, instead, consider the best measurement for the use case. Often in responsive design this will be relative measurements though.

14. Remember not all interactions require jQuery.

:hover, :active, :focus and more. Learn them, wield them like the awesome tools they are.

You probably already use these and know them well. But if you're working on something in javascript, it's easy to forget and use jquery or similar to do it instead.

15. Combine properties

Properties such as font and background can be combined. It's worth using the combined versions for simplicity such as:

background-color: rebeccapurple;  
background-image: url(/images/logo.png);  
background-repeat: no-repeat;  
background-position: top left;  

Could be:

background: rebeccapurple url(/images/logo.png) no-repeat top left;  

16. Avoid unnecessarily long selectors

Sure, referencing body #content .sidebar a works, but would .sidebar a work just as well?

17. Always test your ideas.

Developer tools allow us to test our ideas live, why wait to compile or ftp a file to a server to test your idea for a fix. Change it live in the developer tools and you'll have instant feedback.

18. Browser test too!

With complex modules, check ideas for them as you're going in browsers you think may be problematic, this will make things a lot easier when you return to fully browser check it later.

I've written more about browser testing here.

You can also use Can I Use... to find out browser support for new CSS properties etc. to find which browsers are likely problematic to start with.

19. Avoid specific browser hacks.

Try to find the cause of the problem, rather than a quick fix that may lead to further problems. You may find it's a problem in your CSS and you can work around a problem easier than just hacking it.

If you have to use a hack, explain why in a comment, make sure that in a month when you return to this project you'll know why you added it in.

20. Format your CSS in a clear and uniform way.

This one is a somewhat personal preference, but I try to always write CSS in the same way. I use 4 spaces for indentation (some people use tabs), I separate each selector onto a new line as I believe selectors are kind of the most important part of the css definition, and each property onto a new line.

You can see more of my style choices for CSS in the following post.

Can you expand this list past 20? Leave a comment with your own anti patterns or advice.


Enough with what not to do...

Continue to Part 2 for how to structure your CSS and more tips.


If you disagree with this list or do you have your own suggestions? Leave a comment below and I'll try to reply quickly.