December 14, 2024

10 Tips for Writing Better CSS

Writing your first piece of css code can seem really weird if you’re used to working with tables, or just haven’t written code before. In this article I want to talk about 10 different ways you can write proper and clean css code as well as streamline the process and ensure you’re getting the job done as quickly and efficiently as possible.

1. Always start with a CSS Reset

Writing CSS code can become a bit mundane when you’re having to write specific code over and over again just to get various browsers to display your layout the same. That is where CSS Reset’s come into play. With industry leaders like Eric Meyer releasing a pretty kick ass css reset stylesheet, there’s really no reason to not get all of your browsers ‘back to zero’ and build off of it. Some people have said that css reset stylesheets aren’t needed (Jonathan Snook being one of them), but once you get used to the reset and what items you’re coding, it becomes much easier to ensure that every browser is displaying items properly.

2. Indent your css rules for easier scanning

When you’ve got 500 lines of css code to sift through, it can become straining on the eyes. So, instead of writing out the css code like this:

.classname {
background: #FFF;
border: 0;
color: #252525;
float: left;
margin: 0;
padding: 0;
}

You can indent the rules to make scrolling through the file and finding the proper css classes and ID’s easier.

.classname {
	background: #FFF;
	border: 0;
	color: #252525;
	float: left;
	margin: 0;
	padding: 0;
}

3. Comments are your very best friend

In the spirit of keeping your stylesheets clean and easy to read, comments are going to be a great way for you to keep things structured and clean. By commenting out blocks of code, the scanning process we mentioned above becomes another 10X easier because you can scan and look for items such as the header, sidebar, content and footer code because you have each section of code commented like below.

 /********** HEADER code here **********/

Doing this will not only save you time scanning but will be great for your clients when you pass along the code – they’ll be able to find items easier, fix items themselves and not have to email you 4-5 times a week for simple 1-2 minute changes. The benefits of clean css code goes much deeper than making the file look pretty.

4. One Rule = One Line … Multiple Rules = Multiple Lines

Following the simple rule above, you can cut down on the clutter in your css files drastically. Below you will see the two different ways you can write your css code out – some people swear by putting everything on a single line, but I tend to believe in the above mentioned rules: one rule = one line, while multiple rules = multiple lines.

.classname { border: 0; }

.classname {
	background: #FFF;
	border: 0;
	color: #252525;
	float: left;
	margin: 0;
	padding: 0;
}

5. Stay consistant with your code

I’ve not only stayed cosistant in my css styles throughout stylesheets I’ve written, but if you look at the various css code I’ve displayed in this article, you’ll see I have actually stayed consistant with them. It isn’t something you’ll tend to visually notice on a daily basis, but over time you’ll begin to pick up patterns on how you write specific lines of code and it will throw you off if you ever write something different. It makes things harder to find and runs your time up when you could have easily cured the problem by sticking to a specific style of writing for your css stylesheet files.

For instance, if you’re writing everything in blocks of code to separate different items of the page for easy editing, keep with it. Don’t change the way you write your code every time you write a new stylesheet. It’s just not practical.

6. Separate your hacks and conditional elements

Some people will swear against using any css hacks and scream something like “if the user can’t upgrade his browser, to hell with him!” – which we all know is not something everyone is in the position to say. So, writing conditional elements and various css hacks in your files becomes pretty much routine. But the idea that all of it needs to be in one file is wrong (in my opinion). Separating them from your main style.css file will allow you to make edits and adjustments to the hacks and conditional elements easier, without effecting your main css code.

A sample of how to separate your files could be like the code below, which would give you a separate stylesheet if your viewer is using any internet explorer browser less than IE8, along with your main style.css file and a print.css file (make sure you add the proper “” characters at the beginning and end of each line in the code below):

     link rel="stylesheet" type="text/css" href="/css/style.css" media="screen, projection"
     !--[if lt IE 8]
       link rel="stylesheet" type="text/css" href="/css/ie.css" media="screen"
       ![endif]--
       link rel="stylesheet" type="text/css" href="/css/print.css" media="print"

7. Learn (and use) shorthand code

Shorthand css code will allow you to speed up the writing process, cut down on clutter in your stylesheets and will allow you to find things much easier. So, why do so many people still write out their css in a long hand format like this?!?!

.classname {
	margin-left: 1px;
	margin-right: 2px;
	margin-bottom: 4px;
	margin-top: 1px;
}

Writing the above code in shorthand format allow things to look so much cleaner. Shorthand code also follow the clockwise writing format – so each number (as seen below) goes like this: top, right, bottom, left.

.classname { margin: 1px 2px 4px 1px; }

8. Create and use a table of contents

Writing in a table of contents in the beginning of your stylesheet will allow you, as well as anyone else viewing your css file, to find where the specific items in your code are before they even have to scroll. Need to find and edit your content code to change a color of a specific piece of text? Looking at the table of contents shows you that it’s the third header down in the css file. Coupled with the rule from above about adding in commented areas to separate blocks of code, this will help keep your code lean and mean – plus, very easy to edit.

/*****************************************************
1. HEADER code
2. NAVIGATION code
3. CONTENT code
4. SIDEBAR code
5. FOOTER code
*****************************************************/

9. Keep your class and ID names easy to follow

There’s nothing worse than going to edit a piece of code, only to find that they named their css code like this:

.wackyblueline5 { ... }
.leftsidesection { ... }
#bodyleftcurve2 { ... }

Picking the proper naming structure for your css classes and ID’s can help you dig through your stylesheet files as well as your html files, to edit the code. I would recommend sticking with names like this, which keep things clear and easy to understand:

.sidebar-title { ... }
.postwrap { ... }
.main-navigation { ... }

10. Alphabetize your css code for easier reading

This is one tip that I’ve just come to realize is actually worthwhile and one that I’m beginning to use on a daily basis when writing css code. Alphabetizing your rules will allow you to easily jump in, find the proper line of code you need to edit, change it and move on. Check out the code below and see how the beginning letters of each line go in alphabetical order, which allows you to easily scan and find the proper line. Looking for font-size? well, you know where F comes in the alphabet, right? So finding it in these lines of code will be much easier.

.classname {
	border: 1px solid #dedede;
	color: #000;
	font-size: 18px;
	line-height: 24px;
	margin: 48px;
	padding: 0;
	position: relative;
	z-index: 101;
}

What about you? Any tips for us?

I know the readers here are highly skilled so I would like to pass the baton on to you and let you weigh in, in the comments section with what your thoughts are on these tips and also share tips of your own. I’m looking forward to finding out what you think works best. I hope you enjoyed the article and would love if you spread the word through your various social media profiles. Thanks!

Share

52 Comments

  1. Rudolf Bos Reply

    I Also indent ID’s within ID’s, so I can see which elements are each other parents.

    Also I set the standard tags above in the CSS (h1, h2, a, p, ul) and the classes onderneath (.imgleft, .imgright, .clear).

    And i don’t sort the css code on alphabet but on relativity. Like this:

    #container {
    width: 400px;
    height: 100px;
    padding: 10px 20px;
    display: block;
    overflow: hidden;
    }

  2. Tom Hermans Reply

    multiple rules > multiple lines only makes your whole document longer and makes it harder to grasp..

    hence, if the rules fit one line, usually not more than 3 rules, they stay on one line.

    You first are looking for the selector, then for the rules applied, if you have to scroll back and forth all the time, this is not easy..

  3. Patternhead Reply

    Can’t say I agree with all of these tips.

    I think teh most important thing is to to have a consistent way of doing things that makes sense to you. That way you’ll find it easier to work with the code in the future.

  4. Mark Gilleeney Reply

    I quite like to use tab spaces between my rules and values. I find it makes the CSS a lot easier to read:

    .Example
    {
    border : 0px;
    margin : 0px;
    }
    .Example2
    {
    display : none;
    width : auto;
    }

  5. Bryan Yurasits Reply

    I disagree with rule 6. When working on a large site with many developers and many css files it becomes too difficult to track down if and where someone has a hack. Keeping the hack directly below the proper selector reduces confusion.

    1. Oliver Reply

      I agree completely. Maybe for small projects it seems a good way to organize your CSS, but for websites with complex design elements definitely keep it all in the one CSS file.

      It won’t always validate but in the real world with real deadlines and budgets what matters is getting the site online and functioning cross browser. The most efficient way to accomplish this is by keeping the CSS all together, rather than sifting through hundreds of lines across multiple files. This is especially true if working with a team on a project and you have to keep sending updates of multiple files rather than just one.

      1. Jeremy Reply

        agreed. keep hacks with original whenever possible. if I throw something into an IE-only css file, then the orig css file gets a comment that there is a hack applied and in what file.

        if the hacks are the only things keeping you from validating, then understanding that is better than validating if it costs $100s to workaround. I promise 99%± validation to clients, on the understanding that with as anal as I am about my markup, they should be fine if I spare them a few $100s to have it ‘almost’ validate—unless validation is in their spec up front. in that case, I promise to work as efficiently as possible, but but they’re on hourly rates to fix validation/bug issues that could be solved by a simple fix otherwise.

  6. Simon Day Reply

    Can’t say I agree with the one line – one rule either. I much prefer keeping all the styles on one line and then clearly separate out the different blocks using comments (header styles, left menu styles, content styles etc). Main benefit for me is that I can see ALL the styles pertaining to that section without having to endlessly scroll up and down. I can sit back, look at all the code for that section and then work out where any bugs may be hiding.

    The thought of having to keep scrolling to see the block of styles would give me nightmares 🙂

  7. Kelly Reply

    Excellent post. I especially like the idea of one rule, one line – i find myself fattening up my CSS code with those one-off rules.

    I’ve also found the alphabetical rule very handy, especially going back to old code I’ve written and not having everything in memory of how I did it.

    Thanks!

  8. Brad Reply

    Great article with some good reminder tips, thanks.

    I like indenting my CSS on multiple lines as well. I don’t understand how people can read code all on one line. Whatever works I guess…

    Even more than a Table of Contents, I use CSSEdit and put everything into easy to manage group:
    Layout
    Header
    Menu
    Content
    etc…

  9. Nick Bomufon Reply

    When working with large css files I find it easier to scan when the properties are all on one or two lines.

    I’ve never tried a table of contents, would probably be too lazy to update it since things change too much. I might try this when I’m done though.

    When resetting a css file, I like to reset my general elements and style them to what they’ll actually be rather setting them again in my main css file.

    Usually I have 4 css files to start: reset.css, screen.css (main), print.css, and handheld.css.

    Alphabetizing would take too much time.

    Always use shorthand whenever you can. This save so much time.

  10. Justin Reply

    I don’t like all the spaces. I like everything on one line. Much smaller and quicker for my eyes.

    .class {border: 1px; margin: 0px 0px 0px 0px; font-size: 12px;}

    So much more clean to me.

  11. Elmas Reply

    I almost never use multiple lines. I find it much easier on the eye when it’s a one-line code (whenever possible -> almost always). Then i just indent the entire class for the children elements, just like i would do in html.

    #header{ padding:0px 20px; height:120px; color:white; background:black; }
    #header a{ … }
    #header .something{ … }

    Regarding the alphabetizing, i do not do such stuff, i just have my own logic (which simply came to me over time) on how to sort those declarations. I start width display, with, height, margin, padding and such layout parameters (between themselves in no particular order), then i move onto the content (color, font etc) and then background, border. Makes sense for me and i always know where to look when trying to find some property. A short example can be seen in the #header above.

    1. ambrooks Reply

      I use the same rules when grouping my styles.
      although I usually have each group on a new line.

      #selector {
      display;float;width;height;margin;padding;
      font;color;text-align;
      background;border;}

      #alt-selector {if;only;one;group;}

  12. nauman Reply

    nice info, I’ve been using reset thing since long and found one new thing for me (which is old) that my images getting border on click, so i tried almost every thing then

    img a{
    outline: none;
    }

    property for done it all 🙂

  13. Jeremy Winter Reply

    One good tip, if your code is all a mess and you want to automatically format it to be alphabetized and in shorthand you can use the firebug plugin from Firefox.

    If you open firebug and click on the css tab, it will display all of your style sheets in a nice organized fashion. You can then copy that code directly over to your sheet.

    Two things to note, it only keeps -moz-border-radius, not the other two rounded corner formats. Also it does strip any indentation you have already.

  14. Mike Smith Reply

    Thanks for all of the awesome comments everyone. I’m glad the article is well received.

    And thanks, Henry, for allowing me to write for WDL. And the new design is kick ass 😉

  15. Mike Reply

    Great Tips Mike! I find myself using these rules myself frequently. Just to add to what you have already said for those people out there who may find themselves becoming more interested in programming form their css adventures you can actually start practicing by using industry standard naming conventions. For example most developers who program in C# or php use the following naming convention: Say you want to call a div you have created “My Example Div”, the way to do this in industry standard terms would be to start the name with a lowercase word then separate each word by capitalizing the first letter of each separate word. So “My Example Div” would be something like: .myExampleDiv or #myExampleDiv.

    If you get used to doing this in your css coding it will help you if you decide to learn other more advanced programming languages. Plus it is easy and will really save you time because you won’t have to think so hard about how to stay consistent with how you nave your styles.

    Happy coding everyone.

  16. Jason Reply

    I have had the single-line/multi-line debate with a long-time coworker a number of times in the past. He’s a block kind of guy, but I prefer the all-on-one-line approach (still alphabetized, though).

    He is recent convert, though – at least when talking about production.

    https://developer.yahoo.com/performance/rules.html
    (search for Minify JavaScript and CSS)

    On very large CSS files, the speed increase could be significant!

  17. Kyle Reply

    I tend to disagree with rule #4. I find, especially with large sites, that saving space by putting all of the styles on one line makes the sheet a lot easier to navigate. Also, it helps you group styles that affect different areas, for instance:

    #nav { … }
    #nah ul { … }
    #nav li { … }

    #header h1 { … }

    I like to leave a sort of bread crumb to an easily identified container like #nav or #header, but that can get tricky when it comes to specificity.

    I’m going to have to disagree with #10, too. Alphabetically listing properties is pretty much arbitrary. If you want to change the dimensions of a container, you might have to change border at the beginning, then find margin way down the list, then padding, and near the very end is width.

    I suppose this is more of an issue if you’re styles are all on one line. I’ve learned to order css properties by how the affect the element, starting with dimensions (width, height, margin, padding, border), then positioning if needed (position, top, bottom, etc), followed by font stylings (font-face, font-size, etc), then colors/background-images, then misc properties. That way the properties are groups by the part of the element you want to affect. Being consistent (rule #5) is important here.

    I never thought of using a table of contents. That could be really useful for some of my projects. Great idea and great post! Thanks!

  18. Conrad Muan Reply

    I do agree with having a table of contents, and commenting to section off your css.

    One thing I like to do (and I know that this gets very specific) is to have a GLOBAL section just before the other sections and right after the reset.

    /*****GlOBALS*****/
    h1 {stuff}
    h2 {stuff}
    b {stuff}
    and etc

    I also like to import a css file with
    @import url(”)

    Great tips!

  19. roni Reply

    #1 reset.
    ok, lots of talks about that… pros & cons.
    I use a reset, yes… But not Meyer’s… far too heavy. jut a plain margin & padding 0px reset list-sytle-type, none and border:0 on images.

    #4 is no good : 1 rule per line!
    unless you want to have a css file with 1mil lines that impossible to scan and hardly to fully maintain.
    when dealing with big css, if correctly indented and commented, a one line approach will be more efficient. It is to me. 🙂

    I use one line, as long at it stays on me screen viewport, if more then 2 lines. I dont line horizontal scrolling, and need to get all properties at one glance.

    #8 Table of content.
    I don’t believe it has any added value. Just plain maintenance waste and pain.

    #9 yes indeed but why ?
    Because the classes need a semantic approach i.e. class names need to describe element’s content or actions not their styles.

    #10 might come from goo idea but no good.
    better to have rules organized in logical way.
    if use position then right after, the position values. width & height together, all font & text styles together… etc

  20. john Reply

    so how is it that “One Rule – One Line / Multiple Rules – Multiple Lines” is supposed to work at the same time as using shorthand? i think shorthand is stupid and basically against everything else on the list that’s meant to facilitate the reading process, i don’t need to think more to figure out what changes what side, it’s a lot better to just spell it out for myself and others…

  21. rickyH Reply

    I use shorthand except for the background options. I like splitting them up for readability. like:
    h1{
    background-color: transparent;
    background-image:url(“images/a.png”);
    background-position: 100px 24px;
    background-repeat: no-repeat;
    }
    I guess this might just be me though…

  22. chris Reply

    About No. 10, I think it’s not easy to code the CSS like that, you have to think about which value should be first in mind, that’d take some time. It’s not so efficient when you’re coding the CSS, not modifying it.

  23. Patrik Krupar Reply

    I can’t agree with your multiple rules = multiple lines. I know from my experience, the biggest the file is the hardier is it to read it. To split it into more files is no good idea because of to many HTTP requests.

    Anyway great post, thank you!

  24. phong long Reply

    Nice article! The one section I’d have a difference in opinion in is with ordering rules alphabetically. What I’ve found very useful is to instead order group rules visually by type and how they will affect their eventual rendering on a page.

    for example, i would group and order the .classname rules as:

    .classname {
    position: relative;
    z-index: 101;

    padding: 0;
    margin: 48px;
    border: 1px solid #dedede;

    color: #000;
    font-size: 18px;
    line-height: 24px;
    }

    this way, all the positional rules are visually distinct from the layout rules and the typography rules. This order also helps as a reminder of what’s involved in determining the overall rendered size and position of the element.

  25. Christopher Becker Reply

    Nice article, but I think that sorting your css alphabetically is not correct, what I find works best is to sort the css out in groups, everything that has something do with the header will be together, footer the same and so on…

    So you know all the code that belongs together is together, and commenting makes it easier to follow.

Leave a Reply

Your email address will not be published. Required fields are marked *