The Art of Crafting Beautiful Stylesheets

This entry was published on 28 April 2009 and may be out of date.

Crafting beautiful stylesheets is not a dark art. Yes, it takes discipline, commitment and persistence but with a few tricks up your sleeve, you too can be a CSS ninja.

Let me show you a few techniques I use to craft readable, maintainable and easy to debug stylesheets.

File naming convention

I follow a simple file naming convention across all my projects. It is simple and very effective way of maintaining CSS files. I have seen many designers use obscure names such as main.css or style.css for their stylesheets. I think the names can carry a little bit depth so you know what each file does in a quick glance.

Here is the file structure for one of my client’s website:

style_all.css
Contains the CSS Reset and a few more goodies that applies to all browsers and platforms. This is also a good place to place the link colours and styles for elements generated from WYSIWYG editors in the CMS.

style_screen.css
The main stylesheet file that contains the style for the entire layout. We will have a deeper look into this file in a moment.

style_screen_IE7.css
Stylesheet specific to Internet Explorer 7. Most projects I work on does not need a specific stylesheet for IE7 but this is just for sake of understanding my naming convention.

style_screen_lt-IE7.css
Stylesheet that applies to all versions of Internet Explorer below version 7.

style_print.css
The print stylesheet where you are supposed to get rid of all images and present only the nice and clean text.

This convention is very flexible. If you need a specific stylesheet for IE6, for instance, go with style_screen_IE6.css. For handhelds, it would be style_handheld.css and so on so forth.

The commercial CMS system I work with at my agency has a function that checks the stylesheets folder for the files and applies appropriate Conditional Comments automatically. I might release that bit of code in the future (if I can convince my project manager!)

Modularize

Let us have an in-depth look at style_screen.css which is our main stylesheet. This file tends to get very large so it is very important to separate the styles into sections.

I declare the sections in the CSS at the beginning of the stylesheet.

Hint: Press Ctr+F (or Cmd+F) and type in =FORMS and it skips straight to the Forms section. I find this quite a time saver.

Positioning

Define the layout structure and the positioning of the basic elements. The Header, the Content section, the Sidebar and the Footer. The first thing I do when I start coding a site is to get the frame right, not worrying about the details at this point.

Typography

Contains font definitions for global and all general elements. Define the headers (h1, h2 etc) and paragraph styles, the lists, blockquotes and anything that deals with the presentation of text.

Layout styles

Now that the layout positioning and typography is taken care of, you can now focus on the site design.

You can break this down further with sub-sections if this section starts to get too long. Maintaining proper code indentation and hierarchy (which is discussed below) will help unclutter the layout styles.

Other sections

Usually, I create a separate section for the Forms, CMS-specific code etc. Feel free to  create new sections for your own project, depending on your needs.

The advantages of splitting the code into sections becomes obvious once you have to debug or make changes to an old project. You will feel that it is much easier to browse the code and focus where you need to.

Indentation and hierarchy

Top level elements are indented least. The immediate children of the top-level element is indented once. Their children in indented twice, and so on so forth.

Not only does it look pretty and readable, it makes pin-pointing problems a lot easier. Yes, there is a not of white space that adds bytes to the file size but you can always compress the code before you publish.

For example, you are having issues with the Search box in your page. The code must be within the Layout section under the parent Sidebar. With proper modularization and indentation, you will see how easy it is to find what you are looking for.

Categorise, don’t alphabetise

Some designers have said that alphabetizing the CSS properties is an effective way of organisation because it makes maintenance easier. I beg to differ from that opinion. I find categorising the properties by type is a lot more effective.

selector {
  font-size: 12px;
  line-height: 15px;
  text-transform: uppercase;

  padding: 10px;
  margin: 5px;

  background: #000;
  border: 1px solid #222;
}

In the example above, the properties are grouped into ones that manipulate text, deal with space (margin and padding) and block-level visual cues  (background and border).

If the same selectors were alphabetised, this is what it would look like:

selector {
  background: #000;
  border: 1px solid #222;
  font-size: 12px;
  line-height: 15px;
  margin: 5px;
  padding: 10px;
  text-transform: uppercase;
}

As you can see, the readability of the CSS is vastly reduced. I usually place the positioning properties first, followed by text-properties, spacing and the others.

Conclusion

As you can see, this is not much complicated. It is these simple things that can help a front-end developer keep their sanity. Beautiful stylesheets are a first step to coding zen.

Do you have any suggestions for creating beautiful stylesheets that are easy to maintain and debug? Please do share.

Comments are closed.

55 responses to “The Art of Crafting Beautiful Stylesheets

  1. Great post! As a web designer that has written CSS in several different ways (one line, multi line, hybrid, etc), I find it fascinating to know what others do, especially when it comes to making CSS that scales well.

    Breaking it down into separate files and modules is a great way to do that. Personally I used a simple breakdown for different files:

    – global.css has a reset, type, links, tables, etc
    – layout.css has all the structural elements (header, footer, nav, etc)

    Typically there are three layers, but those two are the key ones.

    I’m curious about your file naming—why prefix your names with “style?” If you house them in a folder named “stylesheets” or “css,” wouldn’t it make more sense to keep the names very short and similar (e.g., all one word, always dashes and no underscores, etc)?

    Again, great post!

    1. @Mark Otto:
      I suppose if you keep the files inside a folder, the “style” prefix is unnecessary. I guess the convention uses the pattern style_(media, browser).css and it seems to work well with my team. Even new hires can pick up the convention very quickly.

    1. @Jake: I would guess that the stray checkbox should be placed pretty close to the “Notify me of followup comments via e-mail” line. Maybe it had a rough day and needed to be left alone for a while..

  2. Separate modules is a great idea, something I’ll have to keep on the top of my mind while coding.

    More than one file is also another good option to combine with the module idea, but I’d recommend you have some system in place to combine, minimize and cache these style sheets into one main CSS file that gets served. This will undoubtedly help with site performance.

    A lot of people are doing this already, but I figured I’d write this caveat for those who aren’t too familiar with site performance tactics. This concept is pretty useful in the age of JS widgets, plugins etc…

    1. I couldn’t agree more with the importance of combining and minimizing when you are deploying. This concept is useful for development but not ideal in a live environment.

  3. Excellent post. Must say though that I HATE modular stylesheets. Having to hunt through 2 or 3 different files for selectors for a particular class or id drives me nuts.

    The alphabetizing selectors thing is way over the top. People who do that must organize their socks by color, texture, and material content. Hilarious.

    Otherwise, right on.

    1. @Beckley:
      I can understand your frustration. But I found that isolating problems becomes a lot easier when it is modular. If it is a layout issue, you’re sure to find it under =LAYOUT so you can block out that bit of CSS (without affecting the display styles) and find the solution.

  4. re: Categorise, don’t alphabetise

    I think this is more of a preference than anything, I personally started using the alphabet approach and I like it a lot. But on top of that, your example of the two different CSS blocks, one is spaced out and the other is not. That alone makes it easier to read, not the fact that one is alphabetized and the other one was not.

    However, every designer has their own way that they like laying out their CSS and there is no “right” way to do it. But I agree with the rest of your blog post and it’s great that designers are starting to organize their code and markup a lot more.

    Thanks for sharing!

    1. @Stephen Korecky:
      Yes, it is indeed a preference. But when you place positioning properties first, followed by text-properties, spacing etc, it is a lot easier to make changes.

      I usually categorise the properties and use a an empty line to separate them. That is what increases readability.

  5. Thanks for the excellent post! I’ve learned everything I know by picking stuff here and there on the internet from different tutorials. In the process of course I’ve picked up a lot of bad habits and I’m now trying to unlearn them and develop best practices that will work for me in my own work.

    This is an excellent step in that direction.

  6. I don’t think Indentation and hierarchy is a good idea. It will make our CSS files complex, and even difficult for reading. Looking at your codes above, I don’t realize the readability.

    And about alphabetize, I think it depends. Some properties can be group, but some cannot. The example above is so simple and cannot be a good example for all. I like to alphabetize my properties, so that, I don’t have to think about which group this property belongs to, and so on. Time is gold :). Unless, if there’s an CSS editor can do that automatically, I will change my mind :D.

    1. @Rick Bauers:

      Say you want to change the link colours under #content #comments .item a

      Wouldn’t it be easier to open the stylesheet and scroll down until you find #content and then looking for the anchor under its children rather than scrolling through a flat stylesheet with no hierarchy and spacing?

      Yes it is true that some properties cannot be grouped. I usually place theme below all other groups in the ‘ungrouped’ group!

  7. Nice Article. Thanks.

    I used to code in multi line format. I never used CSS Frameworks, but a recent client of mine introduced me to Blueprint CSS Framework.
    It has single line format and separate style sheets for layout/color/type etc. So, it can’t get more easier to maintain & debug the style sheets. I also use a lot of comments when working with a team. It may take some extra time to organize the css, but its worth it.

    I use Notepad++ for editing css, It has many built in options to automate the formatting process i-e Alphabetizing, converting layout from multi-line to single line, it selects colors of same text i-e classes, Ids etc.

  8. The only problem with your convention is that with high traffic sites with allot of content there will be significant disadvantages of having so many CSS files.

    This is fine for development but it is much better to have one single compressed css file on the production server. There are fewer requests to the server made so less server load and better page load times.

    @Prydie

    1. @Andrew Pryde:

      Most of these stylesheets are placed under conditional comments. So you are only passing 2 stylesheets (screen and print) to non-IE browsers and up to 3 stylesheets on IE. Even though there as many stylesheets, not all being passed down to all browsers.

  9. I’d have to disagree – and agree with the commenter that a lot of this is personal preference – doing a modular CSS file then boils down to how you modularize it – someone else may switch the order, prefer alphabetizing, etc…

    Generally, the way I try to move forward in projects is to establish architecture (one person’s opinion, sometimes ;-)) but it helps keep everyone on the same page and keep things consistent (a problem when you have multiple devs working on the CSS).

    @Pryde – depending on the server architecture you can develop with seperate styles and merge them on the server (I know PHP can do this, I don’t know about Java, but I’m assuming yes).

    Really, I’d say the key is consistency, establishing a pattern (like this one), and clear comments.

    1. @Keif:

      This convention has proved to be very successful with the teams that I worked with. It helps keep everyone of the same page.

  10. Have a “super” CSS stylesheet that includes all the other stylesheets and give this super stylesheet a caching policy that will expire it every xx seconds (I usually use an hour). That way you can add new versions of the stylesheets with different file naming to beat browser caching without having to modify your page templates. i.e.:

    include.css:

    @import url(style_all.css);
    @import url(style_screen.css);
    @import url(style_print.css);

    1. @Meint Post:

      Nice idea. My server side CSS processor adds a last-edit time tag to the filename so each time you edit the CSS, the filename in the modified CSS changes automagically. Say it was edited last on 30 April at 12:15, the generated filename would be style_screen3041215.css

      This method removes all possibility of caching and always produces the latest stylesheet. Very helpful during the development process because the stylesheets are edited a thousand times a day.

  11. 美しいスタイルシートを作るためのテクニック…

    The Art of Crafting Beautiful Stylesheets ≪ Azadcreative.comで紹介されていた「芸術的に美しいスタイルシートを作るためのテクニック」が興味深かったので、簡単にご紹介。
    ファイルの命名規….

  12. Like Stephen above I too have recently started to alphabetise and have found it a much quicker and effective way of structuring my css. If I were to categorise I’d have to think about it too much and inevitably I’d get the order of my categories mixed up; alphabetically order is a no brainer.

    I’ve been building sites using css for over 8 years and I still don’t see the benefits of a css reset (and certainly not one written by someone else). What I would advocate though is the use of a templated stylesheet containing styles you commonly reuse, for example how you set your body font, set img borders to zero etc.

    Indentation in stylesheets is nasty and I’m sorry but this is only going to make troubleshooting harder as I’ll be sidescrolling in my preferred web editing tool.

    Why prefix all of your stylesheets with “style_”? Surely that goes against the whole idea of using a semantic naming convention? They’re obviously stylesheets so remove the prefix.

    1. @Darren Taylor:

      Alphabetising is a preference I suppose. If it works for you, stick to it.

      CSS Reset “resets” all the default styles, across all browsers and all platforms. It truly provides a clean slate for coding CSS. Don’t let the inconsistent default styles across different browsers bother you.

      Unless you are coding on a netbook, I don’t think you would have to side-scroll.
      The CMS we use would not register a file as CSS unless it there is a prefix. I think it looks good that way!

  13. it might just be me but the source code for this page seems to contradict the mindset for this post:

    themes/azadcreative2009/style.css
    /styles/shCore.css
    styles/shThemeDefault.css

    there are styles in the head tag too.

    if being pedantic about work ethics is preached then why does the the source code for this page show otherwise.

    the head tag reveals the following:

    meta [x3]
    link [x5]
    meta [x1]
    script [x3]
    link [x4]
    meta [x1]

    i thought the post itself was interesting and subjective but the author should be prepared to back up these statements with proof of usage.

    1. @CSS Lewis:

      The first group of meta and link are coded by me. The others are generated by WordPress and its plugins. There’s nothing I can do about it.

      Also, the template tag in WordPress only allows linking to style.css but if you open the file you’ll see @import url(‘stylesheets/style_screen.css’); which means I do conform to my own convention.

  14. This is so oldschool (and counterproductive). A better way is applying classes to the body. Like

    body class = “win mac linux ie6 ie7 ie8 ff opera screen print handheld”

    and styling from there.

  15. I don’t see the need for multiple stylesheets for IE6, IE7, and others. Sure there are inconsistencies, but I’ve always been able to work through them so my sites look 99% pixel perfect on IE and other browsers.

    1. @Mike:

      It is true that its possible to code in a way that its it is 99% consistent across all browsers. But with larger and complicated projects, it becomes essential to have different stylesheets for A-class and C-class browsers.

  16. Interesting article.

    I agree that sections and modularizing are very useful, but I don’t share your view about indentation in CSS files. Waste of time, especially if your editor has its own text formating styles.

    As for number of stylesheets – we should care about website performance: many stylesheets = HTTP requests.

    1. @Kristian:

      Like I said earlier, even though there are many stylesheets, you are never passing more than 3 stylesheets to any browser because of the conditional comments.

  17. Thank you all for reading and leaving comments.

    @Mary, @JuanZe:
    Thanks.

    @Jake, @Robert Wictorzon:
    Silly me. Thanks for pointing that out.

  18. good post… i do similar although using different naming convention. and if a project has a lot of ajax forms etc.. .i will create a forms.css on top of the global and layout… i have never found indenting was really needed with css because things are always grouped together and commented before. i think one of the most important ways to organize your code, (and you touch on this) is throught he use of a consistent commenting system. good post

  19. Well, finally someone who categorizes the same way I do: First font-styles, then margin/padding and finally border/background. And everything “exotic” after that.

  20. […] 2. The Elegance of Imperfection 3. 100 Amazing Futuristic Design Concepts We Wish Were Real 4. The Art of Crafting Beautiful Stylesheets 5. Inspired By A Pile Of Crap, Gmail Adds More Emoticons 6. 24 Amazing Music Videos 7. The Unusual […]

  21. Good ideas, but using modular stylesheets isn’t really best practice, isn’t it? Sometimes it’s unavoidable, but in most cases you can avoid a lot’s of code and files.

  22. This is the best article on CSS advice I’ve read in a while. Moving reset styles into their own sheet is a great idea, and certainly one I’ll start using. I already try to categorize my properties, but I’m not very consistent. what I really need is a script that I can run on my css files to re-order the properties into the categories I want. Hmm, maybe I should do that!

  23. I also categorize my style sheets, however, I tend to have typography in one file, layout in one, colors in one, one for IE7, one for IE6, one for resetting browser defaults, and one for styling forms.

    Sounds messier than it is. I promise.

  24. Great article, but besides naming, the indentation and sorting time can be done by using an online tool I stumbled across via smashmag recently – styleneat.com. Definitely a great time-saver!

  25. This is something I’ve been working on getting better at. It’s amazing (a) how out-of-hand a stylesheet can get on a large site and (b) how much simpler modular blocks and stylesheets make things. Great article!

  26. Hello, Nice reading your article! Indeed i found it on Google and i think you have done a great job promoting this! I am really glad that i found your post! Definetlly i will bookmark your site for later refference! All the best!

  27. Thanks for the great article. If everybody would follow a process like this when working in teams, would make thing so much easier. I’m going to implement this naming convention into my next project.