With the introduction of CSS3, and CSS2 now being used worldwide as a standard for web developers it is safe to say that we all rely heavily on CSS as a whole. Planning and organising your stylesheets is essential for creating manageable and beautiful websites. The idea of organising your stylesheet is actually very simple, and there are many ways of doing so, but I find the following is the best practice.
Comment your stylesheet
This should always go without saying, a well commented stylesheet makes it easier to locate the information and syntax that you are looking for. There are 2 types of comments that I always include in my stylesheets.
Info/Update
This is used at the head of the CSS file displaying what the stylesheet is, what site is it for, who wrote it, and when was it updated.
/*--------------------------------------
Info: Design Grid - Main Stylesheet
Author: Darren Jones
Updated: 09/12/2009
--------------------------------------*/
Section Headers
For every section of the site, put a section header above the syntax. This makes finding section specific CSS a breeze.
/*--------------------------------------
HEADER
--------------------------------------*/
/*--------------------------------------
NAVIGATION
--------------------------------------*/
Define your global rules and main classes first
For anything that will be used globally over the site, set it at the top of the style sheet.
body {
background: #eee;
font: helvetica, arial, sans-serif 12px;
}
h1 {
font-size: 1.2em;
}
h2 {
font-size: 1.1em;
}
Order CSS like HTML
If your html header is at the top of the page, and your html footer is at the bottom, then your header should be at the top of the CSS and the footer at the bottom.
Use the correct selector
There are 3 general rules for using the correct selectors.
- Does it need a selector? If not, don’t use it.
- Use a class if the element/selector is repeated more than once.
- Use an ID if the element is unique and only used once in the document.
Name selectors appropriately
What happens if your class=”red”gets changed to blue? Wouldn’t it have been better to name it class=”sidebarlink”? Try and think semantically when naming your selectors.
Group together common elements
If your h1,h2 and h3 tags are all to be red, then it is best to group them together to define the colour.
h1, h2, h3 {
color: red;
}
h1 {
font-size: 1.6em;
}
h2 {
font-size: 1.4em;
}
h3 {
font-size: 1.2em;
}
There are more things you can do to plan and optimise your CSS sheet. We will cover some more techniques and methods in the future.
Discussions