5 Ways to Write Better CSS

5 Ways to Instantly Write Better CSS

Sure, anyone can write CSS. Even programs are doing it for you now. But is the CSS any good? Here are 5 tips to start improving yours.


1. Reset

Seriously, always use a reset of some sort. Whether you are using the Eric Meyer Reset, the YUI Reset, or your own custom reset, just use something.

It can be as simple as removing the margin and padding from all elements:

html, body, div, h1, h2, h3, h4, h5, h6, ul, ol, dl, li, dt, dd, p, blockquote,
pre, form, fieldset, table, th, td { margin: 0; padding: 0; }

The Eric Meyer and YUI Resets are awesome, but to me, they just go too far. I feel like you end up resetting everything, and then redefining a lot of properties on the elements. This is why Eric Meyer recommends that you should not just take his reset stylesheet and drop it in your projects if there is a more effective way of using it. Tweak it. Build on it. Make it your own.

Oh and please, stop this:

* { margin: 0; padding: 0; }

It takes more time to process, and what do you think should happen to a radio button when you remove the padding? Form elements can sometimes do some funky things, so it may be best to just leave some of them alone.


2. Alphabetize

A Little Quiz

Which example would you think is faster to find the margin-right property?

Example 1

div#header h1 {
	z-index: 101;
	color: #000;
	position: relative;
	line-height: 24px;
	margin-right: 48px;
	border-bottom: 1px solid #dedede;
	font-size: 18px;
}

Example 2

div#header h1 {
	border-bottom: 1px solid #dedede;
	color: #000;
	font-size: 18px;
	line-height: 24px;
	margin-right: 48px;
	position: relative;
	z-index: 101;
}

You can’t tell me that Example 2 isn’t faster. By alphabetizing your properties, you are creating this consistency that will help you reduce the time you spend searching for a specific property.

I know some people who organize one way and others who organize another, but at my company, we made a consensus decision to all organize alphabetically. It has definitely helped when working with other people’s code. I cringe every time I go into a stylesheet where the properties are not sorted alphabetically.


3. Organization

You should organize your stylesheet so that it is easy to find things and related items are close together. Use comments effectively. For example, this is how I structure my stylesheets:

/*****Reset*****/
Remove margin and padding from elements

/*****Basic Elements*****/
Define styles for basic elements: body, h1-h6, ul, ol, a, p, etc.

/*****Generic Classes*****/
Define styles for simple things like floating to the sides, removing a bottom margin on elements, etc
Yes, these may not be as semantic as we would all like, but they are necessary for coding efficiently 

/*****Basic Layout*****/
Define the basic template: header, footer, etc. Elements that help to define the basic layout of the site

/*****Header*****/
Define all elements in the header

/*****Content*****/
Define all elements in the content area

/*****Footer*****/
Define all elements in the footer

/*****Etc*****/
Continue to define the other sections one by one

By using comments and grouping similar elements, it becomes much quicker to find what you are looking for.


4. Consistency

Whatever way you decide to code, stick with it. I am sick and tired of the whole 1 line vs. multiple lines for your CSS debate. There is no debate! Everyone has their own opinion, so pick what works for you and stick with it throughout the stylesheet.

Personally, I use a combination of both. If a selector is going to have more than 3 properties, I break it to multiple lines:

div#header { float: left; width: 100%; }
div#header div.column {
	border-right: 1px solid #ccc;
	float: right;
	margin-right: 50px;
	padding: 10px;
	width: 300px;
}
div#header h1 { float: left; position: relative; width: 250px; }

It works for me because 3 properties is about what fits on 1 line in my text editor before wrapping to another line. So just figure out what works for you and be consistent.


5. Start in the right place

Don’t you dare touch your stylesheet until you have written your markup!

When I am preparing to slice a site, I go through and mark-up the entire document from the opening body tag to the closing body tag before even creating a CSS file. I don’t add any superfluous divs, ids, or classes. I will add some generic divs like header, content, footer because I know these things are going to exist.

By marking up the document first, you won’t run into such diseases as divitis and classitis, which can sometimes be fatal! You only need to add in that stuff once you have begun to write the CSS and realize that you are going to need another hook to accomplish what you are trying to achieve.

Utilize CSS’s descendant selectors to target children elements; don’t just automatically add a class or id to the element. Just remember, CSS is worthless without a well formatted document.

*Editor’s Note: I can’t stress this point enough. As Trevor said, don’t even touch your CSS file until the markup is 100% complete.


Conclusion

These are just some of the tips that help me to write better code. This is by no means the end of the list. As I come up with others, I’ll share.

What tips do you have for writing better CSS?


Tags: CSS
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.jackfranklin.co.uk Jack F

    Enjoyed this list, thanks. Personally I write my CSS on one line, but I’m fortunate to have a wide enough screen to fit lots of them on.

    I do need to organise my stylesheet better though for sure.

    Thanks!

  • http://www.shanedj.com Shane

    I am keen on laying out my CSS in a particular way. All my recent built sites are like that although mine isnt! oops! Resetting too is a good valuable practise

  • http://www.patternhead.com Patternhead

    Some sensible advice here. Not everything works for me. Alpabetize is just not needed in my opinion.

    • http://www.iammikesmith.com Mike Smith

      Yeah, the Alphabetize option isn’t working for me either. I have a set way of writing styles and am so used to it, if it was different I’d go nuts.lol

      But I agree, a really nice post

      • http://www.VisualSuicide.com Jan

        I also dont care much about the alphabetizing. I know i should because it really would be a lot more organized but i kind of am to lazy to write down everything following the alphabet.

        But nice and helpful tips here. I like to seperate each area (e.g. Header, Footer…) with commented lines, to get a better overview what the whole area contains.

        Nice!

    • Rajaji

      I agree to that 100%! Alphabetically arranging is just not needed here. Rarely there are more than 5-6 properties in a class or id so to me there is no need.

      I have been lately using the CSS Reset and I am proud to say that now I have much better control.

      Thanks for this very useful article!

    • http://phantomcode.co.cc/card/ PhantomCode

      Imho alphabetising is definitely superfluous. I find it is much more intuitive to list properties by order of their “significance”. For example my stylesheets will usually follow a general order of display, width, height, margin, padding, positioning, background, border, etc. because, to me, the display property is more important that width which is more important than positioning and so on. It’s not that I do this deliberately, it’s just a habit I’ve fallen into that actually makes stuff easier to find.

      • http://phil-cook.com/ Phil Cook

        I disagree, alpabetize has its place in a large pool of developers. Imagine thousands of lines of css and different developers have come along and editted in a different ways, single line, multiple line, alpabetize, random and don’t start me on developers not declaring page specific items instead just thinking .header class wouldn’t already be used elsewhere.

        This advice laid out here is obviously from a developer who works within a large company where organisation of code is vital for saving many man hours.

        However the comments above suggest single or very small team developers. My advice would be the embrace these suggestions if you wish to go forward with your developer skills.

      • http://phantomcode.co.cc/card/ PhantomCode

        Oh, I absolutely agree that I’m looking at it from a single developer’s standpoint. I just don’t personally find alphabetising intuitive. There are, in my opinion, better ways of organising your code. I don’t, however, dispute the fact that there has to be some sort of agreed-upon standard in large dev teams. If everyone just does their own thing it gets messy fast.

  • http://www.startahead.be cccmien

    I tend to use indentation when styling nested (child) elements. It works quite well for me when it comes to finding a specific property.

    • http://hamiltopia.com ham

      I agree. I have started using indentation when writing out my stylesheets and it works way better then I ever thought it would.

  • https://www.xing.com/profile/Bernd_Artmueller Bernd Artmüller

    thanks for writing this article. i am already working this way, but the first tip is great. i’ll consider it on the next projects

  • http://WWW.RICHARDJOHNASHE.COM Richard

    Think I might try ordering my properties. Didn’t like it when I read it but by the time I finished the article I have warmed up to it.

    Also I am one line per property kind of guy but I’m liking the whole if it isn’t more than 3 properties long keep it on one line.

    Cool content as ever NT. Thanks!

  • http://www.thelastknight.co.uk Ben Reid

    1. I always have a reset stylesheet.

    2. I normally order them by my own kind of logic so something like width, height, padding, margin, backgrounds, borders etc…

    3. Organization is key, especially when you have multiple people working on the same stylesheet.

    4. Yes! Essential, I’m a bit OCD with it.

    5. Yup!

    And all my styles are written in one line, I used to do them in big blocks but have turned to the line side!

  • Pingback: Am Rande notiert: Mehr Ordnung im Stylesheet » Der Korsti bloggt

  • http://www.nickreffitt.co.uk/ Nick Reffitt

    Excellent article, I can definately feel a sense of frustration :)

    Good idea to list the properties in a style alphabetically which I’ll certainly use in future projects. I should really be using a reset too :(

  • Pingback: Turulcsirip - Tamas Bogdan

  • http://blog.insicdesigns.com insic

    Cool list of tips. reset is really necessary indeed.

    • crazyaccess

      hi!

      Looking very nice

      • http://www.michalkopanski.com Michal Kopanski

        LOL.

        Didn’t realize Net.Tut+ was a dating site =x

        Cool tips.

  • nutral

    I always use multiple lines, even when its just one property. I don’t really think its necessary to alphabetize all the css.

  • http://www.alessiopiazza.it Pix

    i’m making some experiment about css organization and now i’m all for dividing them by function:

    - one for build a layout (just margin padding… spaces in general)
    - one for typography (anything is about letters and fonts)
    - one for colors (bg-color, line colors)

    in this way it happens sometimes i find mysel writing twice an instructions, and i’m not sure this is even a good way to organize css but as i said before i like to experiment

  • Nathan Davies

    Great tips, though I write the CSS before the site. Allow me to explain. I sketch the site layout(s) and then slice them up on paper, calculating measurements and deciding link behaviour etc. I also have some standard stuff for handling forms layout that appears in every stylesheet.

    Using the sketch and notes I code the style and then the site and test.

    I also split my style – layout and colour into 2 sheets, plus one for print. This makes changing colour really straight forward and ammending layout means I don’t have the colour definitions to scan through.

  • http://selectwebdev.com Stephen Coley

    Concerning #2… separating width and height would drive me up the wall. If I were positioning with top and left, I would want to keep position top and left together as well. I think #2 might have just been a personal preference. It seems kind of counter intuitive.

  • http://frederic-soler.fr Fred Soler

    Essential to work in team.
    Nice.

  • http://creativevoi.com/ Son NH

    I agree with Patternhead. Alphabetize is good idea but not necessary and sometime waste your time in my opinion. When you write CSS, sometime you don’t know which property should be put to the code. You can only alphabetize the CSS once you know exactly all properties of each selector.

    • Rob

      Exactly! When I write CSS, I don’t know which properties I’m going to use for each CSS style, so alphebetizing doesn’t always work. And. I’m certainly not going to go through 200 CSS styles to start re-arranging and alphebetizing properties. But I do think organization is helpful in anything that we do.

      • http://cfmlx.blogspot.com Arowolo

        Alphabetizing properties is not going to work. but Alphabetizing selector, classes or Ids might work.

        Organizing your css by commenting sections of your style sheet should just do fine.

        Great job…

  • Spence

    Nice article, think putting them in alphabetical order is a bit over the top though!

  • http://dollarthis.com Shuja Shabandri

    Nice post.

    Regarding #3
    You can use @group style

    /* @group Header */

    .css-code-here {}

    /* @end */

    Good CSS editors like CSS Edit, coda and i think many others support this style of grouping.

    These groups actually show up in the sidebar using which you can easily navigate.

    • http://donnamiller.net donna

      @Shuja Good tip I didn’t know about! I use CSS Edit and I’ll try the @group style, sounds like it will be really helpful. Thanks for posting that!

  • http://dappled.com.au Jayphen

    Nice tips, but alphabetising is going a bit far I think. The extra time spent thinking about the order of your properties will just slow you down too much for what it’s worth. Editing the stylesheet in the future will also be just that much more annoying if you have to work out where to put in the new property & value. Generally there are no more than 10 properties for each selector anyway, so it’s not like you have to search through a long list to find what you’re looking for.

  • gareth hunt

    This article is a bit of an oversimplification.

    Firstly, there is no real benefit in alphabetising your css. If I’m changing styles related to the box model or positioning of an element then it’s not necessarily any easier to have to skip across the declarations to find the relevant styles. In contrast, many people will use their own ordering. I use one that orders styles on positioning, then box model (from inside to out), then font declarations, etc. A lot of people will group related styles because of the inherent way in which you code. If you choose to alphabetise, then so be it, but a lot of us will cringe at alphabetised CSS too. It’s the same as the “one line, new line” argument…but in this case there is actual logic to organising based on the inherent relatedness of css properties rather than using an external ordering system such as the alphabet :P

    While the case for writing all html before any css is worthy, in practice, it’s not something that experienced developers will do. I’d also guess that people guilty of using too many extra elements are not going to have that much more success either, for until their knowledge of css is improved, they are likely to go back and add extra markup to achieve the desired visual effect. Experienced developers are also going to be regularly diving into the html to add new elements, change the source based on client decisions, and will know how to achieve certain effects with the absolute minimum of html. And if we’re talking about unnecessary or presentational markup, then not using clearing divs or clearing classes should also get a mention ;).

    Good tips as guidelines for beginners or moderately experienced coders, but the reality is more complex and the organisation of css stylesheets if far more down to personal preference and personal ways of mentally organising and visualising documents.

    • http://www.artificialstudio.com Heinrich

      I have to agree on CSS’ing alphabetically. Usually there are only 5 or 6 lines that are being used in a div / class etc. We should stop being lazy!! Otherwise great article. I always try and keep my stylesheet together in a way where I’ve got everything together. Always good to get some CSS tips! You’re never too old or too good to learn!

  • http://www.webexpedition18.com Nikola

    nice tips, thanks

  • Patrik

    Awesome post, thanks!

  • http://www.jauhari.net/ Jauhari

    CSS Rulez! ;)

  • http://xobb.citylance.biz Xobb

    I’m not very experienced with CSS, so I find it useful. Thanks.

  • http://www.danharper.me Dan Harper

    Good post for beginners. I started alphabetising my properties recently and it definitely makes my code easier to skim through.

    However I’ve found myself occasionally having to run through the alphabet in my head to get some in the right order (makes me sound stupid, I know lol).

    • Rob

      Oh DAN! That’s so silly! HAHA..just kidding! You know what…I’ve done that too! So, no worries! I used to do math with my fingers when I was younger.

  • http://shums.info M.A.Yoosuf

    its kind of usefull, i was realy doingh the “A Little Quiz” part i was doing in first way, yeah, in future i will not do in future thank you man.

    small small thiungs are changing me to a profersional guy ;)

  • http://www.drawmyattention.co.uk Amo

    What this article fails to explain is why certain things should and shouldn’t be done. For example;

    Reset CSS – this is used in an attempt to eliminate the inconsistencies between different browsers, their initial default settings of things such as margins and padding and to reduce the number of conditional CSS attributes as possible. Essentially, it helps to make your site look the same irrespective of the browser.

    Alphabetize – more a personal preference than anything else. I tend to write by CSS slightly differently. Starting with the general layout attributes (positioning, floats etc) and then onto line heights, font-sizes and so on – and finally, colours, borders and fills. The logic behind this is that as the CSS file is interpreted by the browser, it’ll handle the layout of the page before the colours and theme elements – so the user sees the page as it’s intended, quicker.

    Organisation – while it’s important to have well organised CSS, there should be a fine line between having a well commented file, and too many comments. The example given in my opinion has far too many comments which add to the file size of the CSS file and simply increases the page load time.

    During development, comments are good – especially if there are a few people working on a single project, however before going into a live environment CSS should be minified sufficiently to compress the file as much as possible.

    I’d agree to some extent about starting with the document markup and then onto the stylesheet, however it’s not always possible with a complex design and in such instances the two are often developed hand in hand.

    An important note that I feel the article was missing was to ALWAYS encapsulate design within the CSS file, i.e. to never have inline CSS in the main xHTML document.

  • http://www.graphicrating.com Andy Gongea

    This topic is pretty hard to cover because everyone has some good practices and behaviors.

    Personally I use the float as the first property followed by the width and height. In this way you can keep the visual side accessible.

    I do use the reset but right now I’m not sure if it is needed.

  • http://www.samplify.be Sammy

    Your quiz example number 1 doesn’t have any logic (or does it ?), so it’s easy to pretend alphabetizing is best. But it is just one way of doing it, there are others. For example, I like to put in this order: everything positioning related (position, top, left, z-index), width and height (if any), margin and padding together, and at the end all the font properties (color, font-weight, line-height, etc). Different logic. Same consistency.

  • http://www.thebookish.info Wordpress theme designer

    I’m really good at CSS, but I’m surely will make use of some of the tips in this piece.

  • http://www.createatwill.com Will

    I tend to Organise my code by both alphabetising and by grouping similar properties. Like Stephen said separating Width & Height is ridiculous.

    I first group all related selectors (e.g width & height & padding; font & text-align & text-decoration etc.) and then organise them in to alphabetical order. When you create a system like this it helps to quickly drill down into your code.

  • http://www.opensourcehunter.com OpenSourceHunter

    Very nice, i will use this info ;)

    greetz

  • Ethan

    Very nice! I ply do most of. These things (I’m so proud of myself!) May I ask, what is divitis and classitis? :P

    • http://www.argraffdesign.com Andy Bishop

      That’s when you encase anything and everything in divs and classes. In reality you can (and should) add ids and classes to other elements as well.

  • http://www.brunoabrantes.com Bruno Abrantes

    Nice post, but, as others suggested, everyone has their own practices and quirks when writing CSS. I personally only use multiple line CSS, even if it’s just one property. I find it easier to read. Oh, and really nice tip on the alphabetization thing. It might not be that helpful when you’re on your own, but when coding together with a group it’s invaluable.

  • garethhunt

    why was my previous post not included?

  • http://www.instantshift.com DKumar M.

    I Appreciate the efforts behind titles but there is nothing which can make you Instantly Write Better CSS But i do admit the point you covered in this post is very essential and important for beginners.

  • http://www.modxguru.com Shane Sponagle

    Good tips. I am happy that I already practice most of them. To alphabetize the properties is a good idea, never thought of that.

  • Phillip Raffnsøe

    Very good list!

    Funny how i never thought about alphabetizing my stylesheets! Thanks for sharing that simple yet extremely useful tip.

    Phillip

  • http://www.alexrighetto.blogspot.com Alex Righetto

    I’m very interested about this topic.
    I’m testing several options to get the “perfect css”:

    these are the rules I use:

    1 style with the less numbers of rules
    2 style with the less number of selector
    3 keep it clear
    4 Selectors have different wheight, so let’s display them sequentially
    ex:
    p
    .myclass
    #myid
    5 indent the elements.
    h3{}
    h3.myclass{}
    #myid{}

    so it’s simple to detect rules.

    6.mainly, selectors are displaied in the sequence they appear in html.

    what do you think about my rules?

    it’s an approach that could be more clear.

  • http://another-perfect-world.org/ Vasili

    I do all of them minus number one. Alphabetizing is so helpful. :D

  • http://www.ediyang.com eddie yang

    Good post~

  • http://www.jamessmith.co.uk James

    * { margin: 0; padding: 0; }

    I’ve seen no convincing evidence that using the star selector “takes more time to process”. If you can back this up with some empirical evidence on how it affects page load time I’ll be more inclined to believe it, but in the meantime this technique has served me well.

    You’re right to be suspicious about how various browsers will treat styles applied to replaced elements such as radio buttons, especially as the W3C specs are silent on these matters. However, these are marginal cases and are exactly what browser makers spend 1000′s of man hours testing and coding exceptions for. In the unlikely event that it does become a problem in a production-ready browser it can easily be worked around.

  • http://www.flickr.com/photos/danielgilles/ Tanaka13 – Créations du Net

    nice tips! thank you ;)

  • http://www.freshclickmedia.com Shane

    Good list for CSS beginners – I think the value of 5 cannot be underestimated.

    • http://www.freshclickmedia.com Shane

      Point 2 isn’t something I’d go along with. Since there aren’t that many lines in the example given, it didn’t take me long to find what I was looking for. Best, in my opinion, to relate styles rather than put them in alphabetical order.

  • Mark Bowen

    Alphabetizing would be good I admit but only if you really really have it bred into you otherwise it really really slows you down.

    Also your question about where is it easier to find the margin-right doesn’t really make sense because :

    1 It is in the same place both times (third from bottom) ;-)

    and

    2 You know what you are looking for so will find it quickly anyway.

    I do agree that it can be nice in much more complex examples but does take quite a while to get used to doing that.

    Nice read though.

    Best wishes,

    Mark

  • http://www.tripleoption.com/ Ryan

    Good call on the alphabetizing. I also agree with using multiple lines. Drives me crazy to open a css file where everything is one line.

  • Gene

    nice!

    i really like it.. :D

  • http://aetus.net/ celebrus

    I feel the whole alphabetical order thing is overkill.

  • Shaun

    A simple but amazingly good list of reminders. Its really easy to get sloppy and let the standards slip!