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?


Related Posts

Add Comment

Discussion 267 Comments

Comment Page 8 of 8 1 ... 6 7 8
  1. violence says:

    realy good advices

  2. 70watts says:

    Alphabetize props? Really?

    If it can be automated, I’ll buy it, but it’s impractical and excessive. How many props do you have behind a selector anyway.

    Organizing selectors though? Golden.

  3. good advise with Reset.
    Thanks a lot!

  4. Marc P says:

    Point 2 is a bit retarded.

    I would say it would take longer to check and remember to keep each letter in alphabetical order than to press (CTRL+F) and find it.

    There’s being organized and then there’s being anal..

  5. Zyend says:

    I like one liner too, as for Organization, I use:

    #header {background-color:fff}
    #header h1 {color:#000}
    #header ul {}
    #header li {}

    etc.. this way, i can quickly find what i need in a line.
    I dont’ agree with 2.Alphabetize & 5.Start in the right place, for new developer, yes it’s logical, but personally I i don’t need it.

  6. Nagarajan P.V. says:

    The font-family tag can also be the part of the style definition defined for all elements so that no need to mention the font-family individually in each and every definition.

    In case if required the style can be overwritten in the individual style definition.

    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; font-family:Arial,Verdana;}

  7. Marcus says:

    Thank you for this tips. I’m somehow an advanced HTML/CSS-Newbie and I didn’t know how to improve my css organisation but now I’ll try to follow your 2nd and 3rd tip.

    Again: THANK YOU!

  8. Scarf*oo says:

    Wow, great post, but I can’t agree with the alphabetization of css properties. I prefer to structure them by importance, or the impact on the visual side the properties create. For example, the position, display, float properties come first, followed by widths, margins, borders and paddings, and lastly come fonts, colors, backgrounds, etc.

  9. Ronald says:

    This is a great post especially the reset, I’ll apply that to my stylesheets, thanks for this great list, helps alot.

  10. DMC says:

    Completely disagree about alphabetizing, that’s just pedantic, and useless. I didn’t find the second example faster to read at all.

    I’m having a hard time believing that your company made a collective decision to alphabetize all css. Sounds like a real fun place to work…

  11. Pantelis Vratsalis says:

    Great advice Trevor!

    All 5 points are quite significant (especially the last one about markup and css files is a huge issue. I used [and am still tempted to do it sometimes] to create both files in parallel, and was ending up confused and with a lot of classes I could had avoided :) .

    I think it might be useful to start on the alphabetical thing, too, even though I think it is minor, since most blocks don’t include more than 8-10 elements, so it’s not that bad to let it look messy there :)

    Thanks a lot again

  12. Erik Reppen says:

    I’ve seen no evidence of the universal selector slowing sites down in any measurable fashion worth talking about. Certainly not any more than adding 80 more selectors to a reset declaration. I think that’s the Yahoo guys going overboard on their efficiency studies. But yeah the ginormous resets are ridiculous. If you want to get good at this, don’t put anything into your stylesheets if it doesn’t have a good reason to be there. Pre-emptive CSS like adding clearfix to every container just makes a mess and creates more potential for unnecessary confusion as to who is doing what.

  13. Mahbub says:

    Organization is tough when you’re writing / updating css randomly. There should be a tool which organizes similar selectors together. And I don’t thing Alphabetize is a common phenomena to write better css.

  14. SammyK says:

    I thought my stylesheets were all BA and all, but – alphabetize! Holy crap! That’s genius.

  15. Nice post. I like everything except for the Alphabetize option. Again that’s my opinion. Thank for a great post.

  16. Tim says:

    I think this article has some good general advice. I personally don’t use resets, though I’ve considered it, and I wouldn’t alphabetize my code. There are certain things for me which I always have together, like margin and padding or width and height.

    Also, I’m not fond of single line method. I find it easier to find things when they’re all on their own line. I compress before I upload for a live site, so it’s not an issue either way for me.

    I would have added learning shorthand css to this list. It can be a huge time and space saver to do shorthand css declarations as opposed to typing out each specific property.

  17. Martin says:

    THANK YOU! I have been messing with my personal website all morning trying to figure out why IE6 was a few pixels off.

    Yes, this noob was using * { margin: 0; padding: 0}

    Changed it to Eric Meyer’s Reset … add an overflow: hidden to my menu and boom, perfect.

  18. Robert says:

    Nice tips, need to start grouping my css

  19. Jenny says:

    I’ll have to add these tips to my stylesheet. They really do look like things would be neater if I did it this way.

  20. Xar says:

    this is cool man!

  21. Jose Fernandez says:

    What’s with all the alphabetizing hate? Personally being a programmer first and a designer second I alphabetize. I find it much easier to work with. If you’ve already been doing this for a few years and have your own system, by all means follow it, but if you’re somewhat inexperienced I would suggest you try alphabetizing for a bit to see how it works for you.

  22. p3t4r says:

    Great tip about the reset.
    After I started using reset stylesheet, coding has been much easier for me!

  23. Eliseu M. says:

    All remember to insert:

    -moz-
    and
    -webkit-

    at the begging of the new CSS3 selectors, like box-shadow!

    Great tutorial man, gratz!!

  24. jerrey says:

    It’s useful! thanks.

  25. Adrian says:

    Great article.

    A query regarding alphabetization…

    I am using a help/PDF authoring tool that has a CSS editor incorporated. The editor is rather unintuitive so you often have to look at the CSS file directly in Notepad (etc) to troubleshoot style issues. Styles are placed in the file in the order that they are defined and because of the various sections it is very difficult to navigate. Anyone know of a tool that will sort selectors in a CSS while respecting the @media section that the selectors are in? The only tools I have found cannot handle this — they treat the @media declaration as a corrupt selector.

    Thanks,

    Adrian

  26. Marcell says:

    Great post! I have to say I have not been the best css organizer when it comes to designing. Now thanks to this article I will be organize when coding.

  27. The alphabetization tip is a good tip.

    I like consistency as well; however you ruined it for me by showing an inconsistent example :) ‘up to 3 on one line’ is not a good stab at consistency. A good indicator is the fact that people will have a hard time formulating your consistency rule by looking at your css.

  28. DemoGeek says:

    I completely agree with you on the one-liner vs multi-liner divide. It should be a personal choice than enforced upon.

  29. Wazdesign says:

    Search for Free CSS toolbox. it make properties alphabetically.

  30. sachin singh says:

    Wow, gr8 tips, i am a beginner but seriousely this helped me alot……. Keep floating tutorials like this

  31. sachin singh says:

    gr8 tips, i am a beginner but loved it…… nice advice…… helped me alot… keep floating tutorials like this..

  32. nice guide thanks for sharing

  33. Shruti says:

    i really like this tips, using this tips will make my css in batter way

  34. I think this was a very insightful article indeed, I enjoyed readying it very much. I know of a couple of people who are going to benefit from this, I shall RT awesome stuff, thank you

  35. Global CSS = n00b FAIL says:

    When I get a template with a lot of global CSS, I ask the project manager to send the template back and ask the developer to do it right. Typically, it’s freelancers and ad agencies who do the worst global shortcutting – developers who don’t do much coding beyond the initial template, and who obviously have no idea what kind of havok their global crap wreaks in CMS systems with WYSIWIG content editors and other third-party controls.

    I despise it when I set a style for a table or tr, but some moron has cut corners, globally styling things like th and td padding, making my perfectly good CSS fail. When you use Global CSS on content-level elements, you take the C (Cascading, remember?) out of CSS.

  36. Regarding the Eric Meyer’s Reset tip, is this really necessary?

  37. I think than a full-blown reset style sheet is nothing more than overkill for a 5-page brochureware site, but on a highly-designed, large-scale website, there is definitely a place for them.

  38. Greg says:

    why not minify and alphabetize all in one step

    http://www.barryvan.com.au/2009/08/css-minifier-and-alphabetiser/

    make you Style sheet the way that makes sense to you and then for the production environment minify and alphabetize.

  39. Nice post, but even better is the discussion it created and feedback provided from various levels of expertise and preference.

    Have to agree with those that mentioned that Alphabetize is more of a personal preference than a element of writing better CSS.

  40. CSS Madness says:

    Thanks for the post. For CSS reset I usually go with Eric Meyer’s

  41. RonnieSan says:

    Very nice tips. I’ll start using them. Although I think for consistency sake, I would use multiple lines for all properties. Then create a minified version for production.

Comment Page 5 of 5 1 ... 3 4 5

Add a Comment