April 24, 2011

Best Practices – CSS Stylesheet Formatting

Question by Justin Niessner

This may seem like a strange question…but here goes:

I’m currently working on creating a fairly large site using table-less design/css (obviously the best way to go). Unfortunately, I have a requirement that is completely out of my control that states I must have only one stylesheet for the site.

In some regards this is better because it forces me to think about style re-use pro-actively while designed the pages. On the other hand…the stylesheet is becoming monolithic and I’m quickly losing myself trying to find styles I know I’ve already defined.

I’d like to do myself (and anybody who has to work on the site in the future) a favor and make the CSS as readable and easy to update as possible. That’s where you come in. I’m looking for formatting/organizational suggestions/best practices.

Somebody out there has to be better at it than I am.

Answer by Hexxagonal

Why not have multiple stylesheets on your development boxes, but have them merged into one in your deploy scripts.

Answer by Starx

I seem to have a different type of CSS Coding Style. I tend to apply a pattern similar to programming.

Here is a sample markup and the way I style them.

<div id="menubar">
   <ul>
      <li>
        <a href="#">Test</a>
      </li>
   <ul>
</div>

<div id="footerMenubar">
   <ul>
      <li>
        <a href="#">Test</a>
      </li>
   <ul>
</div>

CSS

html {}
    body {}

   #menubar {}
      #menubar ul {}
          #menubar ul li {}
              #menubar ul li a {}


   #footerMenubar {}
      #footerMenubar ul {}
          #footerMenubar ul li {}
              #footerMenubar ul li a {}

Of course, some of you will raise a topic about the file size, but I gain much more efficiency and readability using this pattern that I am willing to compromise a little bit of file size. Furthermore, it also gives a idea of the position where a particular markup lies in the HTML file also.

(P.S, Same answer can be found here too.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!