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
  • Pingback: CSS中属性的书写顺序 - 岁月如歌

  • Tom Hudson

    Number 5 is especially important. Marking up your document before hand allows you to minimise the number of classes (and IDs) you’ll end up using: makes you cognisant of what the eff you’re doing in structuring the content of your document. Then the design really does become independent of the structure while simultaneously enhancing the functionality of the structure itself.

  • Pingback: 5 modi per scrivere meglio i CSS | Webquadro.it

  • http://www.heliumestudio.com carlosvm

    Hahaha…
    Today I’ve found a new word…. :(

    ORGANISE!!

    Sounds good.. I will try it in my new project.

  • Pingback: 5 tipp hatékony CSS-ek írásához - pbes

  • http://5.madbe.net covax

    Great article.
    Always gives me a confidence boost when I read through articles like so and see that methods I already use are being encouraged.

    However, I can’t say I have ever ordered my properties. Maybe I should? Do not really see the point as I have never used so many properties for one element that I can not see all above the fold and just spot the required out….

  • Pingback: Joshua Jones Design Blog » The Weekly Spotlight - 2/20/2009

  • Pingback: Quickies: better CSS « 0ddn1x: tricks with *nix

  • http://www.rizqtech.net Rizq

    Good Post !!!

  • http://adrian-rodriguez.net Adrian Rodriguez

    Thanks for the help. I have been practicing most of these tips and just recently started doing the very first one in resetting everything. I like to use more than one line of code when I am defining more than one style to the element. I usually just do something like

    div {
    margin: 0;
    }

    Even for one line, because it’s just what I have been used to doing, only because it helps others find the styles easier in my css when everything is not bunched up together.

    Thanks for the tips!

  • Julie Berlin

    This tip might be useful for some of you. I have a basic stylesheet that contains my reset css, almost all of the (non-deprecated) html element names, basic class names that I reuse in each project, and microformat class names but with just basic or no style rules. It serves as my starting point for new projects, saves me some typing and it ensures that my styles will usually be in a certain order that I’m used to.
    I too like to put my style properties on their own line and I usually order them according to my own logic, not alphabetically; I will put declarations that relate to position and size first, then margin and padding, then borders and background, then font..

  • Pingback: 5 Ways to Instantly Write Better CSS | Joey & Liz's

  • http://kerplunc.com/ Nick @ Kerplunc

    I don’t bother with a reset. The default styles are sometimes useful, and there for a purpose. I just remove them as I go/need.

    I also write my CSS all on one line, because I have 1680px of screenspace for them :)

    As for alphabetasizing stuff, I don’t bother, because it’s all on one line, it generally takes slightly longer to find the stuff I need anyway. I try get it right first time :)

  • http://jessevlasveld.nl Jesse Vlasveld

    Most of these tips are excellent. Although I can’t quite agree with the alphabetizing, which I think is more of a personal preference.
    I like to put the positioning elements in front, like floats, width height and margin, followed by the colors, borders, etc.

  • Pingback: Shared Items - February 22, 2009 : Horizontal

  • Pingback: CSS中属性的书写顺序 — qybaby Blog Life

  • http://www.joernroeder.de Jörn

    I will create a structure with some imports:
    @import url(reset.css); /* reset */
    @import url(layout.css); /* grid and so one */
    @import url(typography.css);
    @import url(navi.css); /* style group */
    @import url(form.css); /* style group */

    I have only one file in the code
    global.css

  • Iain Collins

    My thoughts on the advice here:

    Tip 1) Suggesting to always use a CSS reset and same time as lambasting people for resetting elements they don’t need to as if it’s ‘expensive’ operation (which it’s not) while at the same time advocating resetting elements that don’t need to be reset is contradictory.

    You will need to test your layout in all likely target browsers if you want to be sure content is displayed as intended in them, blanket CSS resets are not away around that. As such, it makes the most sense to change CSS properties as required than to always define a bunch of redundant markup.

    Tip 2) In both examples the line required is on the same line so it takes the same time to find both whether you use your editors find function or look line by line. I do not agree with the assertion that one example is quicker than the other.

    You will lose a lot more time house keeping than you will ever save if you are so retentive you must manually arrange elements so that they displayed alphabetically at all times.

    If it really bothers you the sensible thing is to start using an editor/macro that does that for you (or something like Coda that can abstract the CSS markup to a GUI, or use Emacs/Textmate/E-TextEditor etc) rather than to advocate keeping it in order manually.

    Alternatively, you could knock up a script in a few lines in Perl/Ruby/Python/etc to do that for you (it’s very simple), assuming you can’t find one that exists already.

    Tip 3) Putting all your CSS markup for different elements of a page on one big style sheet like that is not a very good idea – this is really where using @import() comes in.

    Tip 4) “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.”

    Regardless of your view, suggesting there is no debate is implausible. Advocating consistency and then being inconsistent yourself is again contradictory. I agree with the general point in that I can’t say I care either really – but if I was as with Tip 2 I would use an editor to handle the details.

    I will say that if there are a bunch of you working on the same sites, talk about it and come to a consensus if turns out to be an issue. Techniques for resolving naming conventions and syntax formatting debates are very well covered elsewhere already.

    People will inevitably disagree, all you can do is come up with the least contentious solution, and naming conventions are a far thornier issue than syntax.

    Tip 5) I don’t think this is a big problem, people don’t usually write CSS before markup so I don’t think you need to explicitly advise them not to.

    However…I will say that suggesting waiting until markup is “100% complete” is impractical. Even setting aside the dynamic nature of websites, the state of CSS support in mainstream browsers often mandates the creation of theoretically redundant elements – or the repositioning if existing ones – in order achieve a desired layout (without say, resorting to JavaScript or other unwieldy workarounds).

    The lamentable MSIE 6 is the worst offender still in wide use in this regard – the order and nesting of of elements can be crucially important with some common layouts because of it’s numerous shortcomings.

  • Pingback: 5种方法立刻写出更好的CSS代码 - 怀念1997年的秋天 - 个人生活心得,工作感悟,wordpress技术交流 - Power by 3284265.cn

  • Pingback: Write better CSS under 5 “Good” practices. « Lasitha Silva’s Web’log

  • Pingback: 5 metoder til at skrive CSS | Jayj.dk

  • http://www.ouiea.net JoTGi

    Thank you for your post, it’s really useful for people who are begining like me :)

  • Danish Jalbani

    Amazing post, I love your writing style

    I also follow some rules that are helpful.
    What I do is that I try to make use of ID wherever I think it is possible because I guess it makes my work easy, I just assign the ID to the part I want styled that way.

    Just a suggestion.

    Again, the post was awsome.
    Thanks

  • Pingback: Dark Side of the Carton » 5 Tips to Write Better CSS

  • http://www.blogopreneur.com Kian Ann

    Another tip I use very regularly is to indent my CSS.

    Just like HTML or programming code, indentation does help a lot to understand the structure of the CSS code.

  • gvtbs

    我是一个来自中国的前端开发人员,能交个朋友吗?gvtbs@163.com

  • http://dreamweaver-magic.blogspot.com/ Brian

    Well I am pretty new to website design generally and CSS in particular so just reading these notes was a useful exercise and has given me plenty to think about.

  • http://shipin.blogbus.com shipin

    这真是一些不错的建议,非常感谢.
    但是关于第二点(2. Alphabetize)我不是很认同,虽然这样的排序在查找方面有一定的优势,但是我认为在排序上应该把修改频率高的属性排在前面比较好,因为很多时候我们要修改块级元素的宽高和间距属性,或者给它们添加背景属性,我们是否应该按下面的顺序写会更好呢?
    div#header h1 {
    background: #FFFFFF url(“http://”) 0 0 no-repeat ;
    float: left;
    margin-right: 48px;
    padding: 10px 0 0;
    width: 100px;
    border-bottom: 1px solid #dedede;
    color: #000;
    font-size: 18px;
    line-height: 24px;
    }

    • http://www.eraxa.com Sirwan

      i was just wondering why do you write in another language if you read it in english?

  • http://www.markuppoet.com Amal

    there is no technical befit for arranging code alphabetic order. sometimes its may create problem.think about the box model technique.

    * {margin:0; padding:0} i don’t found any problem with this. moreover its easy, shorter and professional.

    others technique you may use for better practice but have no technical benefit.

    thanks for your post.

  • Pingback: 快速写出较好CSS的5种方法 | 前端观察

  • http://www.stvproductions.net ST Verschoof

    This helps me so much. I am lousy at organizing in my css sheets, and indeed I have trouble finding certain values. I am going to follow these rules!!! Thank you!

  • joe cannes

    Frankly, * {margin:0; padding:0} works fine with lightbox, the Eric Meyer Reset example and your reset example causes too many problem with lightbox.

    I used the 2 examples and was having problems with lightbox, and finally found out it was the reset css causing lightbox to misfunction

  • http://abhijeetpathak.blogspot.com/ Abhijeet Pathak

    Very informative article. In case of small rules, I usually prefer writing them on single line, but indention is also no problem due to good editors like Notepad++ etc.

  • http://www.front-end-developer.com Vidal

    When your css is a mess,….apply source-formatting works nice too in dreamweaver….

  • http://harshamv.com/ Harsha M V

    Wow.. I am a much organised person… i am feeling like organising my just created website… Thanx Davis

  • mrdata

    what about validation?

    I think validation should be the 6th way this article should include.

    It’s easy with CSSEdit:

    Open the style sheet you’d like to validate.
    Open the Validation inspector
    choose File > Validate
    or type ⌘-shift-V
    If there are any errors, click on them to go to the offending piece of CSS.
    After fixing things (or breaking them more), repeat step 2.

  • http://twitter.com/nszumowski nszumowski

    this has been open in my browser for a couple of days and finally just got to reading it. great post, #2 is an awesome idea, I kind of want to look over my old code to spruce it up a bit! as for the global reset, i’ve never had a problem with anything and this is the first time i’ve heard someone mention an alternative. if your suggestion speeds loading time, i’ll give it a try! thanks again!

  • http://www.glarenmei.multiply.com Dinna

    hi! i’m an alien with this CSS stuff. and i’m having problem with my multiply page. i love writing poems and my main problem is that with all my poems posted at my page, it’s very awful because of the very long list of poems. so i tried looking for a css on how to put the poems in a scrollable box. i searched at google but i can’t find one that would teach me how to put my blog in a scrollable box. that’s why i’m hopeful that you would spend time to help me out with this one. btw, my multiply page is http://www.glarenmei.multiply.com. see for yourself how ugly my blog box is. so please help me out with this one. thank you and more power to you. your tutorial here is awesome and very helpful especially to CSS newbies like me.

  • http://www.vmalni.com Buzzlair Voufincci

    cool but i wonder it aint work for small tag :D

  • http://micromarketing.ru Alexey Novikov

    Alphabetizing is evil. Group selectors by meaning, not by letters.

    By the way, it is fast enough to find meaning-based selectors. Sometimes faster than is they are alphabetized

  • http://micromarketing.ru Alexey Novikov

    Jörn, more files is worse. More files — more server requests.

  • Pingback: Creative Bookmarks: Best of February 2009 - Tutorial9

  • http://www.katproductions.co.uk Kat Thompson

    Great post – as someone self taught and only normally working with smallish websites I feel heartened to know that I’m generally doing ok with css. I’ve always found it easiest to get the basic structure mark up done and then when adding the css after the site just seems to spring into life. Cheers.

  • Pingback: Murmp - 5 Ways to Instantly Write Better CSS

  • Pingback: 快速寫好CSS的5種方法 « MUKI space*

  • Pingback: CSS und HTML - Sauberer Code « Necrowxrst’s Weblog

  • http://www.pontbren.com Andy

    Good post but I disagree about alphabetising. I think its easier to group related / similar properties together, such as margin and padding.
    In section 4 you write div#header and div#header h1 instead of #header & #header h1 – why? This is understandable with classes where you may add specific styling dependent on the element but not ID’s which need to be unique.

  • Pingback: 43 Incredibly Useful Collection of Tutorials, Resources, Insiprations « the gypsy

  • http://www.svrdesign.co.uk Graeme

    Thanks for the advice!

    I’ve just been learning css and web design for a year now so these tips will come in handy. I will use your stylesheet structure from now on I think.

  • http://www.lukillas.com.ar Lukillas

    Great! I’ve just taken some of these tips and started using it on a little project I’ve started at work. Thanks!