homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor
Home / Forums Index / Code, Content, and Presentation / CSS
Forum Library, Charter, Moderators: DrDoc

CSS Forum

Is there a correct or standard way to write your CSS?

 10:43 pm on Jun 9, 2009 (gmt 0)

Hi Guys

I am teaching myself CSS and was going though some of my CSS style sheets trying to tidy them up and standardize them (I have 3 web sites)

I was wondering if there is an accepted standard on how to layout your style sheet.

Eh the order of divs like header, body, content areas etc.

And the various styling elements such as margin, padding, borders, background colors etc.

Or does it not matter ?



 12:18 am on Jun 10, 2009 (gmt 0)

No "standard", but there is common sense. Group like elements and attributes to make it easier to maintain the css!


 12:35 am on Jun 10, 2009 (gmt 0)

This is a pretty good question, one that I think really gets down to style. Any organization is better than a lot of what I've seen - just helter-skelter addition of ID's and styles to the bottom of the file as needed. It's almost like you can track the development from start to finish. :-)

I do it like this, most of the time, with comments. For structural elements, form the same structure as your html.

/* anything that affects overall page - right at the top, class OR id */
body { }
body.no-background { }

/*page structural elements*/
/* Most of these will be on-on-a-page anyway, hence ID's.*/
#header { }
#main { }
#inner-wrapper { }
#sidebar { }

/* general styles - used throughout */
h1,h2,h3 { }
p,ul { }
.medium-text { }
.small-text { }
.emphasis { }

/* specific elements */
/* for example, applies only to forms but can be used anywhere on site */
form { }
input,textearea { }

/* specific, isolated instances for pages */

/* main page only */
/* Some of these, after development, get
pulled out into their pwn sheet, for example,
general.css and main.css */

/* rates page */

/* last of all, links */
a:link { }
a:visited { }
a:hover { }
a:active { }
#header a:link { }
#header a:visited { }
#header a:hover { }
#header a:active { }

As for style, many CSS gurus will hate this. I like to keep my "short" selectors on one line:

.emphasis { font-weight:700; color#ff0000; }

More complex ones, single tab multiline (visualize the margin space as a single tab)

#main {
width: 95%;
max-width: 1024px;
min-width: 800px;
margin: 0 auto 0 auto;
padding: 0;
border: 1px solid #00000
/* blah blah bla */

This is my "working CSS." For deployment . . . . I save as much as 20 KB by removing all necessary white space and newlines. If you view source, it looks chaotic . . . which is fine by me for copy-paste monkeys. :-)

A related subject, if my working CSS approaches 300 lines, I begin to worry if I'm over-thinking things. I'll break up the CSS into smaller files, as mentioned for the main page example. It's a delicate balance between what takes longer, one large file and one hit to the server, or multiple smaller files with multiple hits to the server?

Anyway, that's what I do.


 12:59 pm on Jun 10, 2009 (gmt 0)

I often find it easier to use an order based on what I set: e.g. I want a certain shade of red to be used for borders, fonts, backgrounds as a theme in a site: set them all in one spot, regardless of the selectors used.

Similarly, If you set a font used for certain things (e.g. titles, highlights and whatnot: set it in one spot only.

There really is no need to group all settings on a given selector together.


 1:57 pm on Jun 10, 2009 (gmt 0)

This is my "working CSS." For deployment . . . . I save as much as 20 KB by removing all necessary white space and newlines. If you view source, it looks chaotic . . . which is fine by me for copy-paste monkeys. :-)

Is saving 20KB worth the hassle? It doesn't seem like much of a saving particularly now most people are on a broadband connection. Is this something I should be doing?

Also can I give an opinion on indenting the css code, to me it makes it less readable. I much prefer to have everything ranged left, each item on a new line and plenty of comments and white space so I can find things easily. I try and keep every thing in a logical order rather than just adding things on the end of the code because when you add on the end you may affect other code that you don't want changed.


 5:24 pm on Jun 10, 2009 (gmt 0)

I try and keep every thing in a logical order rather than just adding things on the end of the code because when you add on the end you may affect other code that you don't want changed.

"logical order": For CSS the "logic" is specificity, not so much order. Actually order is only relevant when specificity makes no difference anymore.


 5:31 pm on Jun 10, 2009 (gmt 0)

Is saving 20KB worth the hassle? It doesn't seem like much of a saving particularly now most people are on a broadband connection. Is this something I should be doing?

Not for one person, no.

But if you have a million hits, that's money saved on bandwidth costs.


 9:26 am on Jun 11, 2009 (gmt 0)

My method is similar to rocknbil's, almost scarily so except I have the links at the top in the general section, and the page structural elements would either appear at the top of their related "section" or be put in a separate stylesheet with just their widths margin/padding etc so they're not to be touched. If they're in a separate sheet then the sections in my main sheet are still commented and go with a favoured flow..

(etc.. this is because the order of sidebars can usually be swappable in my templates, so I don't think about them as left, right..)

things that might get added at the end are true exceptions or classes that could get applied anywhere.. e.g. highlight, note

I don't use a big reset, but if I did it would be at the top under html/body

I too keep my "short" selectors on one line ;)

I don't like the indented>indented code (i.e. HTML style multi indents), I find it very difficult to read, I can scan read CSS though so I may be an exception :o.

For me section comments and logic work just fine. When developing however, with the long rules I do like to indent the selectors by a space or two for some reason, with a space between each ruleset (again like rocknbils #main example but I don't use a tab, one or two spaces at most)

But I almost always remove this excess for production, I will if required provide clients with one fully commented indented sheet as well as a "clean one" if they wish to minimise it.

I'm in the "use as few as possible" sheets camp (grr to Drupal ;)), preferring not to have to switch between multiple sheets when I know what element something applies to I know where to find it in one sheet without having to guess which bit of its formatting would be in which sheet! (a color key at the end of a stylesheet along with search and replace works just fine for "constants") - However in some large organisations that also isn't always the best so am easy and will go with the flow, there isn't really a 'one rule fits all' answer ;)

I definitely wouldn't go the alphabetical sorting route, can you imagine looking for form {margin: 0; padding: 0;} is it down beside #footer {} or 3 years ago did you code your #header form {} more explicitly because it's horizontal? (under H instead of F), what about the login form in the sidebar was it the default - under f or under s - #sidebar form {}?

As for the order of selectors within the rules, it doesn't really matter and you might like to alphabetise them, but again I usually have width, margin, padding, border together at the top as they all affect the width/spacing (Box model) - font style/type/size - color/background - anything that naturally goes together stays together though perhaps in no particular order

Think about what will happen when you have to go back to the sheet, or pick up someone elses.. Develop your own best practice that you will still understand in a few years time.

I know that most experienced CSS'ers tend to section things and even if it's not with the flow of the document it's easier to find a whole section with specific selectors than it is to reverse engineer specificity if it's all over the place.

While the efforts of some suggest it would be good to have a "Standard" coding practice, (indent>indent, like HTML indenting) With the Hot Trend these days emphasising overall Page Load speed and HTTP requests, I can't see it happening myself and will still go for the shortest route.. CSS specificity and minimal whitespace.

interesting question, thanks for bringing it up :)



 2:57 pm on Jun 11, 2009 (gmt 0)

Saving bandwidth is great.

I organize style sheets in the order as they appear in the page. HTML elements and classes which apply globally at the last. Page structure at the top, classes and elements relating to the particular structure following it and next structure. This makes easy for me working and editing. And also used single property like

background: url() no-repeat top center;

background-position:left top;



 4:08 pm on Jun 11, 2009 (gmt 0)

Obviously, from all of the above, the answer is to organize however it makes sense to you, it is a very subjective thing (and eventually you WILL obsess over how it looks).

I have an associate who puts a space between every single attribute/element and 2 spaces between each select ... it drives me MAD! But that's his choice.

Always consider "SCALABILITY" when planning. Learn the wonderful value of setting and using site-wide defaults. Eventually you will find yourself recycling and modifying the same basic css file over and over, so keep it lean by using css shorthand and not unnecessarily repeating elements. (shorthand eg: "margin: 0 .25em" instead of "margin-right:.25em; margin-left:.25em")

When I first started, I repeated "font-family: Arial, Verdana, Sans-serif" in every header, list and many selects. One day it just dawned on me to use it once in "body {font: normal small/1.5em Arial, Verdana, Sans-serif}" - thereafter the only time I ever designated a font-family was when I wanted it different than the default.

There are the occasional elements with rules of required order, like the link pseudo-classes:

a:link, a:visited, a:hover, a:active.

From the w3c school:
"Note: a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective!

Note: a:active MUST come after a:hover in the CSS definition in order to be effective!"


 5:40 pm on Jun 11, 2009 (gmt 0)

Is saving 20KB worth the hassle?

In itself - no. But trim off from 3K to 20K on all your page images, make decision to combine an image instead of "splicing" it to remove one more request to the server, include only the CSS files needed for a given page, it all adds up. One example was reducing a 320KB graphically heavy page to under 100K by trimming every element possible with no visual loss of quality. So yes, I think it's worth it.

My method is similar to rocknbil's, almost scarily

This is because most of what I know of any value I learned from UK's finest, SuzyUK. :-)


 8:35 am on Jun 12, 2009 (gmt 0)

make decision to combine an image instead of "splicing" it to remove one more request to the server

@rocknbil by this you mean to use a single image for the various graphic elements of a site and use the css positioning instead of having different images? (eg: background-position: 100px 100px;)

[edited by: SuzyUK at 9:44 am (utc) on June 12, 2009]
[edit reason] unintentional smiley ;) [/edit]


 4:57 pm on Jun 12, 2009 (gmt 0)

you mean to use a single image for the various graphic elements of a site and use the css positioning instead of having different images?

Sometimes yes, sometimes no.

If optimizing two "spliced" images adds up to the same amount f KB, I would rather leave it as one image and reduce the server request by one. It all depends . . . shave where you can shave.


 1:21 pm on Jun 13, 2009 (gmt 0)

As mentioned, there is no right way, only a sensible style. Here's what I prefer:

CSS rules are put in this order:

1) CSS "reset" or super-global stylings. One that I'll do right at the top is:

2) base element selectors, like a, a:hover, img, p, h1, h2, etc. Also any other "reset" kinds of global stylings. They go at the top too.

3) styles grouped according to the feature they apply to, especially if they're subselections inside a container element like this
#navbar .tab{...}
#navbar .separator{...}
#navbar .secondary{...}

I'll put a couple of extra line breaks between these sections, and sometimes a comment if that breaks the page visually

As for indentation style, I mix it up:
a) if it's one selector and one rule, I'll leave them on one line:

b) if it's one selector, many lines, I'll break and indent:
. color:red;
. background:yellow;
. border:1px solid blue;
dots added to preserve spacing

Other tips:
- using sprites is awesome. Do it whenever you can.
- in a surprising number of situations, a background image on an element is more flexible than using an <img> in the markup
- a well-styled border-bottom can be more pleasing than styling an <hr>
- CSS shorthand notations are next to godliness

And... when you're all finished, keep your human-readable copy in development, but run your CSS through a minifier to squash out all the whitespace and comments before putting the file on the server.


 4:08 pm on Jun 13, 2009 (gmt 0)

FWIW, and with all due respect:

Isn't the best example possible.

First: A font family is a list of fonts and it really ought to end in a generic font. Linux, FreeBSD e.g. won't always have it -it's a Microsoft font (licenses needed for others to use it)-, bundled with Windows since Windows 95 and Window NT.

If you only list one font and it's not available, odds are courier is going to be used by the browser ... Now you would not want that, would you ?

Generic fonts are defined here:

Secondly if you set it on e.g. a body it'll inherit on it's own with less load on the browsers ("*" matches any element, inheritance is supposedly faster - not that it'll make all that much of a difference IMHO)

So, I'd change that into e.g.:

body {
font-family: tahoma, "Myriad Pro", helvetica, sans-serif;


 3:19 am on Jun 14, 2009 (gmt 0)

I go for css organization - I separate it into a number of files - generally these correspond to themes. For example looking over one of my sites I have:
style_layout.css - page layout
style.css - page display (when it is not part of a specific component that might be added or removed)
style_page_size.css - hacks to handle small resolutions
style_sifr.css - sifr specific styles

I *alway* have a layout file and a generic file. The generic file I usually group by header, column 1, ..., column N, footer with comments and a small area of white space separating. I usually have additional files that are parts of packages I have added on at some point but that may change versions or be removed.

This makes it easy to - for instance - kill the styles I added for sifr if I remove if from the site. What sucks about this is that left to its own accord the above generates a lot of overhead due to multiple requests and comments.

That is why I also have:
style_wrapper.php - a php wrapper which takes all of the above, combines them into a single file, and minimizes their size.

I highly recommend the wrapper approach as it shrinks the total size significantly (I use yuicompressor to clean up and compress but there are probably a number of options there) and eliminates the multiple requests. Also organizing into different files is sometimes a useful tool if - for instance - you want to inline your layout code so that the page renders faster on the first load.


 1:14 pm on Jun 14, 2009 (gmt 0)

Just a few pointers from me. First, I attempt to put the CSS in my style sheets in the same order as they'll be on the page.

Your classes should describe what they do, not how they look. So class="warning", not class="red".

And I prefer to format things like this:

/* main div area surrounding everything */

margin:0 auto 0 auto;
border:1px solid #00000

1. One comment line describing what it is, clear line after.
2. All extra spaces deleted...left aligned, no spaces anywhere else


 3:24 pm on Jun 14, 2009 (gmt 0)

Using a CMS system I also divide my CSS into different files. Only called were needed.

Layout of the CSS I use mostly 2 parts also with 1 line comment and no spaces:
1=layout settings
2=styling settings


 9:08 pm on Jun 15, 2009 (gmt 0)

One thing I didn't see in the other replies:

Make sure to put any styles that don't validate or hacks at the end of your sheet; this will help you avoid cross-browser issues


 1:18 am on Jun 16, 2009 (gmt 0)

After I write the thing, I minify it all to one single line. As few intermittent characters (tabs, spaces etc.) as possible. It will shave of quite some bytes (up to 25% on a decently sized CSS file), saving you data and increasing speed. If I ever need to edit, I'll just de-minify using a regular expression match.

To hell with layout best practices; I code for the user.


 10:42 pm on Jun 17, 2009 (gmt 0)

I think the best way to order the declarations is sorta by how CSS prioritizes them.

First, should be all HTML element declarations, such as body, a, p, div, span, etc. in order of appearance and/or most logical order

Then comes content classes/IDs (and sub-elements) in order of appearance.

When it comes to spacing... one blank line between each definition if they aren't very related, but if they are very related, just a newline to separate. Curly braces: no spacing or line breaks, I think it's pretty stupid. After semi-colons and colons I'd usually put a space, but sometimes it's just easier to just put a space only after semicolon.

Order of properties not a biggie, but makes sense to go display/float first, then size, then padding/margin/border, then pretty much anything else.

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / CSS
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved