This blog has moved here: | FOLLOW ME ON TWITTER @woork
Tuesday, March 11, 2008

Write a well structured CSS file without becoming crazy

Big CSS files can be complex to manage but a good structured code can help you to make your life simpler.

This is a descriptive post about how to write a well structured CSS file. I already spoken about code readability in CSS files, but after several most specific requests about this argument (mainly about the difficult of some readers to manage CSS file with a big quantity of layout elements), I decided to illustrate the process I use in these cases.
I experienced, proceeding without "order" or a clear vision about what you want to realize can be harmful and you risk to add, change, remove classes and properties, with the only result to have untidy code with a lot of unused elements on your final product.

Before you start writing directly CSS code, I suggest you to prepare a "draft" with all sections your site will have. Then follow these simple "rules" to optimize your work:
1. Be simple
2. Be "elegant-code" oriented
3. Be methodic

Be simple

Avoid everyting is not strictly necessary. Don't use six <div> layers if you can obtain the same result with only two. If you think a certain design structure is too complex to be realized with CSS probably you are mistaking something. Try to find another way to implement it. In general, almost everything is simple. We are too complex.

Be "elegant-code" oriented
Indent your code to highlight dependencies between CSS elements, use white spaces and comments to separate portions of code logically different. Use clear, in-line, comments like this:

Don't write a "book" about a div ID called #column-left. If you coose the right name, it's clear enough.

Be methodic
Use the same name to identify the same sections in all your projects (#logo, #navbar, #left-column, #footer...). Group CSS classes for typology and add CSS properties in alphabetical order for improve the readability. Once you find the right method to proceed, reuse it every time you work on a new project. So, the code will be more "familiar", more simple to manage and you'll write it more fastly.

Before start coding ask you: where do you want to go?
This is a good question you would to do before opening your preferred editing software. The only things you need now is a pencil, an eraser and a white paper where to trace a "draft" with all main sections of your site:

At this level, you have not to add too many details in your write-hand "draft": size (width) of every single element (in pixel or percentage), paddings, borders and margins are enough.

Let's go. But first reset CSS default browser styles
This practice reset the default browser style for HTML standard element (h1, p, ul, li...). Recently I read a lot of interesting post about this topic. I don't know you... but the only "common" tags I use in my project which required a "reset" are:
body, h1, h2, h3, p, ul, li, form
Nothing else. Very rarely table elements (<table>, <tr> and <td>). In any case, for a complete overview about CSS reset technique take a look at these links:
- Yahoo! UI Library: Reset CSS
- Eric's Archived Thoughts: Reset Reloaded

Start writing CSS code
Now, you are ready to proceed. My typical CSS code looks like this:

Nice, elegant and clear :) Because the code also has a certain charm!

Page structure
Ok, now you can start to design the site structure adding the main sections. If you prepared a "draft" with the site layout it's very fast. Whichever choice you do in terms of layout (liquid or fixed), I suggest you to define a class .container which set one time only, the width of all element which it contains. In this way, if you want to change the width of the page, you'll do it for a single CSS element (.container) instead of all elements which it contains (these elements will fit automatically with the new size).

This is for example my welcome section (in green below the navbar):

...and tese are my column-left (with post body) and my sidebar):

When a CSS definition of main site sections is ready, you can start writing HTML code. There is nothing simpler, just adding DIV layers with the right ID in the right order:

<div class="container">
<!-- Header -->
<div id="logo"></div>
<div id="navbar"></div>
<div id="welcome-section"></div>

<!-- Main Content -->
<div id="column_left">
<div id="sidebar">

<!-- Footer -->
<div id="footer"></div>


Test it on your browser and if it's ok, you can start to add new details to the CSS code and proceed step-by step, section after section (navigation, sidebar, footer...), to complete your CSS in a well structured way and integrate id with HTML code. Indent code you write to higlight dependencies between all elements of the same class:

This little sagacity increase dramatically the code readability when you have to find a specific element in your CSS code.

Custom Class to the end
In general, if I have some classes which can be applied to more than a section, I add them to the end of the CSS file in this way:

I use a descriptive name for each class which identify immediatly the main properties.

I hope this tips can help you to simplify the way you use to write and manage CSS files.

Related content
Optimize your CSS files to improve code readability

blog comments powered by Disqus
Mini0n said...

Man... You rule! xD
Excelent post! Very good information!
I kinda try to follow those steps, but I confess I've never thought about indenting CSS...
Keep up the good work! =)

BobbyT said...

Hi, very good advice and I almost believed that I can write my own CSS now! By the way, which editor do you use for CSS/HTML writing?

deltawing said...

Excellent advice!

There's a ridiculous amount of stuff on CSS hacks and all sorts of convoluted methodologies, and to finally read something about code maintainability and sensible structuring makes me happy.

Thank you.

Thijs said...

Hi Great article, very usefull!

Isn't it better to use semantic naming in some parts? ie. #content-column instead of your #left-column?

Your left-column name says something about your presentation instead of your content. What if you decide to change your layout by floating your #left-column to the right?

BTW: Wich font did you use for the "written" comments?

Lilysunshine said...

Hey, nice work!
Though, 1 comment about your class .container. As this is the main container on the page, it would make more sense to use id (#container) rather than classes. Ids are meant to be used only once, when classes are supposed to be re-used several times on the same page.
Just a thought ;)

Juan Balari said...

I just start few days ago about this, an your advice us very effect in my learning in web design


Peter said...

you are one of my best teachers! indeed.

Gemma Jones said...

Great article! As a seasoned css developer I've used most of these tips - incorporating them into my coding practice as I went along :) Never indented my code though - going to start today!

I've also found it incredibly useful to keep a 'table of contents' at the top of every css document I write. That way when I need to find something I can look it up straight away with the 'find'.

Phil Thompson said...

Some great points well made.

I have to agree with some of the other commentators, your CSS could be enhanced with more semantic class names - it's quicker and easier (not to mention, more intuitive) to name your class as 'red' if the text will be red but when you come to redesign your site and you want that text to be blue you'll have to update your HTML as well as your CSS - which will add more work.

I also tend to put a brief table of contents at the top of my CSS files as well as a brief update log: The table of contents helps any other CSS developer reading/editing the file to immediately know where to find a given element instead of searching through to find it.

I also alphabetise my CSS rules so
backgound: red;
color: white;
margin: 0;
padding: 0;

So it's easier to find things for me and other developers.

Jack said...

Great post. The best I've never read about this topic.

Brian said...

I can't believe I'm not the only one who alphabetizes their CSS rule. Awesome.

It should be noted, however, that on rare occasions alphabetizing will make a bit of a mess of things. I can't think of any examples off hand, but I swear it's happened before.

Anonymous said...

What is the font used in the screenshots of the code?

Antonio said...

@anonymous: the font is Kelly Script.

Steph said...

Nice post! I just cleaned up my code a bit, thanks!

...but do we *have* to indent our code? To me, it just looks messier. :/

Enrico said...

Excellent work, I'm decidedly becoming a regular reader.

What about Blueprint?

PS: la foto va meglio, ma c'e' ancora lavoro da fare.

Huge thumbs up


Antonio said...

@Enrico: :)))

Joe said...

I'm an official subscriber to your blog. Another excellent and well-written article.

Antonio said...

@joe: thanks joe! I really appreciated :))

Wayne Hoggett said...

I'm not sure using a background image for a header (logo) is a good idea. Shouldn't the logo always be clickable and redirect to the homepage?

camoire said...

Great tips, I personally like to keep all my css rules for elements on one line, and in alphabetical order. It really makes rules easy to find once you get used to it.

Indenting related styles is definately a must do.

Anonymous said...

It was nice a post!

Another Soldier For Christ said...

Excellent write, though I know how to write and structure CSS pretty well, you have given me a few pointers.

Anonymous said...

The best post I never read about this argument. Excellent!

Anonymous said...

What do you use to draw your diagrams?

Darcy said...

Very good info. I just started indenting my styles as you illustrate, it makes a huge difference. It is also good to add a table of contents to a css file if it is really big. That way, upon opening the file, if it has been awhile since you have worked on it or if it is a new coder they can jump around sections easier right away.

Anonymous said...

Nice read. However, may I ask why you are using PX for fonts over EM? And also why you are not following some sort of line-height vertical rhythm?

Jon said...

Excellent article.

I'd also add that once you have completed a few sites you will notice the sections of css which is used regularly and usually are repeated each time.

Take a copy of the page along with the css and use it as a template to start with next time.

sefokuma said...

Un artículo excelente.

Rich said...

This is a great article. I have been searching a long time for a standard starting point for my css files. This is beautifully laid out and your instructions on why you things are fantastic. You have made me a loyal reader of you blog.

Rob said...

Nice article but I prefer to write the common styles at the begining because in certain elements declared after them it is possible to override some styles.

Thanks for sharing it :)

Anonymous said...

Sorry but, what the font of the code, not the comments?

And what editor you use?


Antonio said...

@anonymous: I use Dreamweaver to edit code for my web projects.

What font do you say? The font hand-written I use for the pic is Kelly Script.

Anonymous said...

i'm talk about pink and blue font (are the same)...

Antonio said...

@Anonymous: the code used from Dreamweaver is MONACO, size 7px (I use a mac)

Matthew DeClaire said...

Clean style is a sign of professionalism. Remember that maintenance is the majority of programming, so keep in mind those who will be reading your code.

Create Maintainable Code with a CSS Styleguide

Ralph said...

Yes, i write my own CSS with my own structure. Your arcticle is great and i will read it, perhaps i think about my own css-structur ;)

emre said...

You guys remember that indenting code makes the file bigger (every space costs one byte :] ). So when you finish a project, good thing to do would be reducing the size of .css file, e.g. by entering CSS validator and copy->paste the code to the file.

Joe Levi said...

@emre: You're correct about adding size to the .CSS file using this method, but you haven't considered the impact of HTTPcompression (which if you're not using, you should be!). HTTPcompression lets the web server talk to the web browser using compressed text rather than plain text, spaces and tabs compress down SUBSTANTIALLY. (This approach will also compress your scripts and your html/xhtml, if enabled to do so.)

Just two bits from a Professional Web Developer.


Joe Levi said...

Something else to consider is using multiple classes to style your text... You have a .small-gray-text class and a .small-black-text class (or something along those lines). These classes contain redundant code (setting the font-size of each class).

Rather than make redundant classes you could use a .small class which sets the size of the element, and class each to define the colors (ideally you wouldn't given them color names, you'd use names that describe the text like "emphasize" and "deemphasize" etc.).

Using this method you'd apply the two styles to the element class="small emphasize" (using a space for separation). The normal rules of the cascade apply, so the first rule will be applied first, followed the second, third, etc. on down the cascade.


Daxion said...

I used this approach on my... first project. After that I started to write (almost)scrambled code. The reason for this is that indenting, adding new lines for each property and new lines for braces, ends up with a very looooong stylesheet. You have to scroll a lot to find something. Instead, you can always find the main rule or id and read the code to the right. You can always use a formatter to clean it up for the scrambled impaired :P

Adeel Fakhar said...

Great Job! I really impressed!

nilesh said...

Nice article :)

can u help me regarding how to write the css name?

For example:
.blue12 {

but it is not proper way to write the css name.
waiting for u r response


Patrick said...

Good article in general, and I'll use some of the tips here.
However, I prefer semantic class and id names in CSS.
Also, I always code the site's (X)HTML first, not the CSS first, not ever. Sure, I may have an idea about general CSS rules, but I don't even touch that file until the page structure is down as (X)HTML.
Thanks for the article.

roni said...

Allow me to disagree with the naming of a class as .small-grey_text{...}

Imagine I use your approach a text color #999. My client does not like the color any more and insists for having that text in red.
Then what ?

I want to move my text color to #f00, right ?
So I will have .small-grey-text{color:#ff0;}
It does not make sense anymore does it ?

I would rather use a class name that describe the action/properties of the DOM Element rather than it's style as Patrick just pointed out :
"I prefer semantic class and id names in CSS"

Let's imagine this class is used to enhance some text.

.enhanced-fact{color:#999;} and if my client wants this move to red, just change the #999 to #f00.
The class name still makes perfect sense, sematicaly still correct and still understanable and readable.

Just one example, but revamping a whole page/site having dozens of complex classes named like that will really fastly loose you.
(using same approach for a text with props : small, italic, black, tahoma, bold, uppercase to be revamp into completely different I think you can easily see the problem)

The article has been published quite some time ago, but I just got the woork-handbook pdf and red the article.(nice work btw, thanks for free dwnld)

Suparna said...

Really excellent post! I really like your teaching style...very simple...very clear...and easy to follow and understand.

Emily Rose said...

Great blog design and nice post! Especially part about resetting "CSS default browser styles".

Welcome to my blog about articles writing. Thanx.

  • Twitter Follow woork on Twitter
  • RSS Feed Subscribe to stay up to date
  • Podcast Coming soon...
  • 0 delicious lovers save
Share your links. Do you want to suggest any interesting link about web design or tech news? Submit your link.
Submit a News