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
  • Andre

    Err on the side of over commenting and maintain good versioning. That means, don’t touch the stylesheet until you’ve backed it up.

  • http://jengermann.com Jen Germann

    Nice post! I definitely incorporate these things into my stylesheets, except for the alphabetizing. For me, it’s hard to think about borders before I’ve set dimensions and padding. I think as long as it’s consistent, the stylesheet can still be neat and organized.

  • http://gainingaccess.net Patrick Wood

    Thanks for the helpful post. am somewhat of a novice when it comes to writing CSS. Definitely some good ideas in the post and comments about keeping your CSS more consistent, organized, readable, and leaner.

    But there is something I do not understand and I hope someone can explain it to me. How can you write *all* of your markup without at least knowing what your basic CSS is going to be?

    How would you write markup for columns without knowing the CSS? Would it not be better to at least have the basic CSS layout already prepared and use it in your markup? Is there some technique I am missing?

  • http://www.korbinianpolk.com korbinian polk

    #5 is the only point worth to be emphasized

  • Pingback: elucid(blue) » Five Ways to Write Better CSS

  • Pingback: Tyler’s Blog » 5 CSS Tips and 10 Harsh Truths About Corporate Websites

  • rachid

    Good to know,thanks

  • KP

    What about tidy CSS? I see a lot of people recommending the use of CSS Tidy and similar utilities to speed up load times and optimize sites. The use of such a utility seems to go against a couple of the principles you’ve mentioned in this post – alphabetize and organize.

  • nick

    Alphabetizing is clearly not a way to write better CSS.

    It makes plenty of sense to set your width and height first so you know what everything following is working inside of. Having to scroll your eyes up and down to find height/width is not useful to actually writing better CSS.

  • Pingback: http://net.tutsplus.com/tutorials/html-c …

  • Pingback: Great Happiness » Améliorer votre CSS

  • http://www.ipoxstudios.com IPOX studios

    Thanks, I’m just learning CSS, so this will help!

  • Pingback: 7 Steps To Write Better Code | MediaVirgins.com

  • Pingback: links for 2009-02-18 | Squirrel Hacker

  • Pingback: links for 2009-02-18 - Square Eyez

  • Pingback: Proj

  • http://www.goldplateuk.com andy

    alphabetizing if there is such word is a bit ocd for me – so is worry about all on one line or not

  • http://virb.com/qeek Sebastian Dadał

    I already do all this… feels good :)

  • http://www.hamroawaaz.com Rahul

    The end line is saving time, and it feels great too when you accomplish that too. ;)

  • John Woods

    OUtstanding! Excellent tips dude!

    RT
    http://www.anonymity.eu.tc

  • http://localhost/ jdzzle

    i usually put the most relevant stuff such as width, height, display, position at the top. then usually padding and margin comes after that. i do most of what this article suggests already.
    i think i can offer a tip: your layout should look like a vertically layered cake in some respect.. granted if you have a menu floating to the left that could take up 2 layers of the cake, but then those 2 layers become 1… *shrug*

  • Brandon S. Adkins

    the “complete your markup before doing CSS” is a very good point.

    however, sometimes i find it easier to follow this in increments.
    in other words, do part of your markup, and then the related css. continue the markup and then fill in the related css again. rinse and repeat. this process works well for me and still results in well formatted documents.

  • Pingback: Order of the Day: CSS Properties | Aloe Studios Blog

  • http://www.cbeauctions.com pcdatadoctor

    Great post, I will have to start doing things like that more with my coding.

  • http://www.carecaprice.com care

    I am ready to doing this, so cool submission

  • http://www.enzy.org Antony Jones

    @JackF

    As happy I am that you have a wide screen and can write all your code on one line, the majority of people don’t, making your code more difficult to maintain/adapt by other people.

    Unmaintainable code is bad code.

    Don’t do it :)

  • http://www.streetdaddy.com Streetdaddy

    FormatCSS is a free online tool for formatting CSS, including alphabetisation of rules and properties: http://www.lonniebest.com/FormatCSS/

    In my experience it has never broken my CSS.

    • http://www.lonniebest.com/News/ Lonnie Lee Best

      Thanks for testifying about my tool!

  • http://www.WarMarks.com Warren Marks

    First tip is great, i would be using it in my next CSS job i do.

    I use multiline css code, it makes me feel easy and at home with css :-)

    I think alphabetic order of properties is just an overkill!

    Yeah commenting and indentation make me feel great when it comes to revisit a stylesheet after some weeks!

    Thanks for sharing!

  • Stephen H

    Alphabetizing your declarations is one of the most ridiculous ‘tips’ i’ve ever heard of.

    For the 0.034 seconds it takes your brain to scan through 5 different declarations to find which one you want, versus the time you would take in re-arranging the declarations is laughable.

    Or do you write your style declarations in that order first?

    “Golly, I sure would like to add the width of my element right now…but it starts with an W and that comes before B and P, so i guess i’ll have to my background and padding declarations first!”

    Give me a break. Have we become that lazy that we can’t quickly scan through 5 short lines of code?

  • Pingback: Graphix | taggle.org

  • http://www.seandelaney.co.uk/ Sean Delaney

    Very informative. I will be applying this steps in my next project which actually starts on Monday…so its nice timing to have found this post today!

    Thanks.

  • http://www.kosdir.com besart

    Great tips for writing better CSS code, Thank you!

  • Matt

    Man, it’s almost like you read minds. This is almost the exact route I take when styling my css.

    It was kind of weird reading it, as I thought, “hey, that’s what I do”.

    I guess the saying is true – great minds think alike.

  • http://apps.jooopa.net Gibi

    Thanks, I’m just learning CSS, so this will help!

  • Igor P.

    Um…. Yeah so the thing about alphabetizing… The margin-right property is in the exact same spot in both examples. So once I found it on the first one, I found it in the second on in 0 time. So bad example.

  • http://yettobebranded.net Micheil

    I must be really odd, I found it easier to find the margin-bottom property in first example of #2 than in the second example.

    Could this just be habitual?

  • http://www.mangst.com mangst

    Very much agree with Consistency. I’d rather have my code be “consistently disorganized” than have little bits of organization here and there.

    The Flickr photos are a nice addition to the article.

  • http://www.crearedesign.co.uk Martyn

    Like the tips but im not overly sure about the alphabetizing the CSS rules. Even If I had enough time in the day that’s probably one thing I still wouldn’t do but commenting on your CSS is a definite must for all coders.

  • http://www.irshadmohammed.com Irshad

    Great post, I definitely need to sort my CSS out. I just started as a web designer so I need to gain experience.

  • Alex

    These are excellent points. But like others have said I personally would never alphabetize the properties. I don’t see the properties as words, rather as what effect they have on my markup. Therefore I start with the structural positional properties (display, position, width, height, margin, padding), followed by the presentational properties (border, background, color, font, text).

  • http://www.videoprofessor.com Css Tutorial Dude

    great tutorial, I am gonna start alphabetizing my properties from now on.

  • Pingback: makin257 - 5 Tips For Instantly Writing Better CSS

  • http://www.blacksnipe.be Angelo

    Gee, I never stopped to think to order my CSS attributes alphabeticly…

    I always use(d) long blocks of comments, so I can see directly where what element is, on first sight, and it always worked for me :-)

    With my latest project, for the first time, I used multiple stylesheets, too… It’s clean and tidy, but it’s a bit of a fuzz, if you’re looking for that one sheet, and you’re getting disturbed…

    Anyway, I think I’ll give it a try in my next project. Thanks for the hint ;-)

  • Pingback: 5 Tips For Instantly Writing Better CSS « Internet Making Money

  • http://www.jonathonvs.com/ Jonathon VS

    I agree to a certain extent (especially with #5!), but some things I think are a matter of preference.

    For example, resetting your CSS is nice in some cases because you get better compatibility with several browsers, but in many cases, you’re really just setting a CSS property to 0 and then setting it again to something else. What’s the point of setting a list’s margins to 0, then setting them to 1em later, when you can cut your code in half by just setting its value to 1em in the first place? By including the reset code, you’re adding code and increasing loading and processing times (albeit marginally) for something that makes absolutely no difference. My advice in most cases is just to learn the default behaviours of browsers and write CSS to accommodate. I’ve come to learn that the more generic your styles are (e.g. element selectors instead of class selectors), the less you have to define styles twice.

    Similarly, I agree with Mark in that alphabetizing your CSS is only handy if that’s the way you think. Typically, in my CSS, I put structural styles (e.g. margins, padding, floats, positioning) at the top of each rule and formatting styles (e.g. bold, colour, font size) at the bottom because that’s the way I think. While it may be quicker to have alphabetical styles when other people look at my CSS, it wouldn’t be any quicker for me. It depends on whether this site created/maintained by me or my Web team.

  • Pingback: NthDesign | Kreativt tänkande inom webdesign | CSS tips

  • http://chrisparaiso.com Chris Paraiso

    Awesome tips. I definately need to start organizing better.

  • http://FragosTech.com George Fragos

    We all have our own ways. Reset is necessary but rather than having a separate section or sheet I prefer to only have one style for each markup. Perhaps the hard way but mine. I hadn’t thought about alphabetizing before. The idea make s sense to me since it makes my code easier to read because of the consistency. I’ve already updated my business site. Truth is that site’s CSS is normally my starting point when designing a client’s site.

  • Pingback: 5 Ways to Instantly Write Better CSS - NETTUTS | Best Web Gallry

  • Pingback: links for 2009-02-19 at James A. Arconati