Forum Moderators: not2easy
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 ?
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.
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.
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.
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.
header
subnav
content
sidebar1
sidebar2
sidebar3
(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..)
footer
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 :)
Suzy
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;
not
background-image:url();
background-position:left top;
etc.
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!"
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. :-)
make decision to combine an image instead of "splicing" it to remove one more request to the server
[edited by: SuzyUK at 9:44 am (utc) on June 12, 2009]
[edit reason] unintentional smiley ;) [/edit]
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.
CSS rules are put in this order:
1) CSS "reset" or super-global stylings. One that I'll do right at the top is:
*{font-family:tahoma}
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{...}
As for indentation style, I mix it up:
a) if it's one selector and one rule, I'll leave them on one line:
a:hover{color:red;}
b) if it's one selector, many lines, I'll break and indent:
a.tab{dots added to preserve spacing
. color:red;
. background:yellow;
. border:1px solid blue;
}
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.
*{font-family:tahoma}
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:
[w3.org...]
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;
}
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.
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 */
#main{
width:95%;
max-width:1024px;
min-width:800px;
margin:0 auto 0 auto;
padding:0;
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
To hell with layout best practices; I code for the user.
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.