How should I organize the contents of my CSS file(s)?

Css

Css Problem Overview


This question is about organizing the actual CSS directives themselves within a .css file. When developing a new page or set of pages, I usually just add directives by hand to the .css file, trying to refactor when I can. After some time, I have hundreds (or thousands) of lines and it can get difficult to find what I need when tweaking the layout.

Does anyone have advice for how to organize the directives?

  • Should I try to organize top-down, mimicking the DOM?
  • Should I organize functionally, putting directives for elements that support the same parts of the UI together?
  • Should I just sort everything alphabetically by selector?
  • Some combination of these approaches?

Also, is there a limit to how much CSS I should keep in one file before it might be a good idea to break it off into separate files? Say, 1000 lines? Or is it always a good idea to keep the whole thing in one place?

Related Question: What's the best way to organize CSS rules?

Css Solutions


Solution 1 - Css

Have a look at these three slideshare presentations to start:

Firstly, and most importantly, document your CSS. Whatever method you use to organize your CSS, be consistent and document it. Describe at the top of each file what is in that file, perhaps providing a table of contents, perhaps referencing easy to search for unique tags so you jump to those sections easily in your editor.

If you want to split up your CSS into multiple files, by all means do so. Oli already mentioned that the extra HTTP requests can be expensive, but you can have the best of both worlds. Use a build script of some sort to publish your well-documented, modular CSS to a compressed, single CSS file. The YUI Compressor can help with the compression.

In contrast with what others have said so far, I prefer to write each property on a separate line, and use indentation to group related rules. E.g. following Oli's example:

#content {
    /* css */
}
    #content div {
        /* css */
    }
    #content span {
        /* css */
    }
    #content etc {
        /* css */
    }

#header {
    /* css */
}
    #header etc {
        /* css */
    }

That makes it easy to follow the file structure, especially with enough whitespace and clearly marked comments between groups, (though not as easy to skim through quickly) and easy to edit (since you don't have to wade through single long lines of CSS for each rule).

Understand and use the cascade and specificity (so sorting your selectors alphabetically is right out).

Whether I split up my CSS into multiple files, and in what files depends on the size and complexity of the site and the CSS. I always at least have a reset.css. That tends to be accompanied by layout.css for general page layout, nav.css if the site navigation menus get a little complicated and forms.css if I've got plenty of CSS to style my forms. Other than that I'm still figuring it out myself too. I might have colors.css and type.css/fonts.css to split off the colors/graphics and typography, base.css to provide a complete base style for all HTML tags...

Solution 2 - Css

I tend to orgainize my css like this:

  1. reset.css
  2. base.css: I set the layout for the main sections of the page
    1. general styles
    2. Header
    3. Nav
    4. content
    5. footer
  3. additional-[page name].css: classes that are used only in one page

Solution 3 - Css

There are a number of recognised methodologies for formatting your CSS. Its ultimately up to you what you feel most comfortable writing but these will help manage your CSS for larger more complicated projects. Not that it matters, but I tend to use a combination of BEM and SMACSS.

#BEM (Block, Element, Modifier)

BEM is a highly useful, powerful and simple naming convention to make your front-end code easier to read and understand, easier to work with, easier to scale, more robust and explicit and a lot more strict.

###Block Standalone entity that is meaningful on its own such as:

header, container, menu, checkbox, input

###Element Parts of a block and have no standalone meaning. They are semantically tied to its block:

menu item, list item, checkbox caption, header title

###Modifier Flags on blocks or elements. Use them to change appearance or behavior:

disabled, highlighted, checked, fixed, size big, color yellow

#OOCSS

> The purpose of OOCSS is to encourage code reuse and, ultimately, faster and more efficient stylesheets that are easier to add to and maintain.

OOCSS is based on two main principles:

  1. Separation of structure from skin

> This means to define repeating visual features (like background and border styles) as separate “skins” that you can mix-and-match with your various objects to achieve a large amount of visual variety without much code. See the module object and its skins.

  1. Separation of containers and content

> Essentially, this means “rarely use location-dependent styles”. An object should look the same no matter where you put it. So instead of styling a specific

with .myObject h2 {...}, create and apply a class that describes the

in question, like

. > This gives you the assurance that: (1) all unclassed

s will look > the same; (2) all elements with the category class (called a mixin) > will look the same; and 3) you won’t need to create an override style > for the case when you actually do want .myObject h2 to look like the > normal

Solution 4 - Css

However you find it easiest to read!

Seriously, you'll get a billion and five suggestions but you're only going to like a couple of methods.

Some things I shall say though:

  • Breaking a CSS file into chunks does help you organise it in your head, but it means more requests from browsers, which ultimately leads to a slower running server (more requests) and it takes browsers longer to display pages. Keep that in mind.
  • Breaking up a file just because it's an arbitrary number of lines is silly (with the exception that you have an awful editor - in which case, get a new one)

Personally I code my CSS like this:

* { /* css */ }
body { /* css */ }
#wrapper { /* css */ }
#innerwrapper { /* css */ }

#content { /* css */ }
#content div { /* css */ }
#content span { /* css */ }
#content etc { /* css */ }

#header { /* css */ }
#header etc { /* css */ }

#footer { /* css */ }
#footer etc { /* css */ }

.class1 { /* css */ }
.class2 { /* css */ }
.class3 { /* css */ }
.classn { /* css */ }

Keeping rules on one line allows me to skim down a file very fast and see what rules there are. When they're expanded, I find it too much like hard work trying find out what rules are being applied.

Solution 5 - Css

I've tried a bunch of different strategies, and I always come back to this style:

.class {border: 1px solid #000; padding: 0; margin: 0;}

This is the friendliest when it comes to a large amount of declarations.

Mr. Snook wrote about this almost four years ago :).

Solution 6 - Css

I go with this order:

  1. General style rules, usually applied to the bare elements (a, ul, ol, etc.) but they could be general classes as well (.button, .error)
  2. Page layout rules applied to most/all pages
  3. Individual page layout rules

For any of the style rules that apply to a single page, or a small grouping pages, I will set the body to an id and a class, making it easy to target particular pages. The id is the base name of the file, and the class is the directory name where it is in.

Solution 7 - Css

Factor out common styles. Not styles that just happen to be the same, styles that are intended to be the same - where changing the style for one selector will likely mean you'll want to change the other as well. I put an example of this style in another post: Create a variable in CSS file for use within that CSS file.

Apart from that, group related rules together. And split your rules into multiple files... unless every page actually needs every rule.

Solution 8 - Css

CSS files are cached on the client. So it's good practice to keep all of your styles in one file. But when developing, I find it useful to structure my CSS according to domains.

For instance: reset.css, design.css, text.css and so forth. When I release the final product, I mash all the styles into one file.

Another useful tip is to focus readability on the rules, not the styles.

While:

ul li
{
    margin-left: 10px;
    padding: 0;
}

Looks good, it's not easy finding the rules when you've got, say, 100 lines of code.

Instead I use this format:

rule { property: value; property: value; }

rule { property: value; property: value; }

Solution 9 - Css

As the actual ordering is a vital part of how your CSS is applied, it seems a bit foolish to go ahead with the "alphabetical" suggestion.

In general you want to group items together by the area of the page they affect. E.g. main styles that affect everything go first, then header and footer styles, then navigation styles, then main content styles, then secondary content styles.

I would avoid breaking into multiple files at this point, as it can be more difficult to maintain. (It's very difficult to keep the cascade order in your head when you have six CSS files open). However, I would definitely start moving styles to different files if they only apply to a subset of pages, e.g. form styles only get linked to a page when the page actually contains a form.

Solution 10 - Css

Here is what I do. I have a CSS index page with no directives on it and which calls the different files. Here is a short sample:

@import url("stylesheet-name/complete-reset.css");
@import url("stylesheet-name/colors.css");
@import url("stylesheet-name/structure.css");
@import url("stylesheet-name/html-tags.css");
@import url("stylesheet-name/menu-items.css");
@import url("stylesheet-name/portfolio.css");
@import url("stylesheet-name/error-messages.css");

It starts with a complete reset. The next file defines the color palette for easy reference. Then I style the main <div/>s that determine the layout, header, footer, number of columns, where they fit, etc... The html tags definses <body/>, <h1/>, <p/>, t etc... Next come the specific sections of the site.

It's very scalabale and very clear. Much more friendly to find code to change and to a dd new sections.

Solution 11 - Css

I used to worry about this incessantly, but Firebug came to the rescue.

These days, it's much easier to look at how your styles are interrelating through Firebug and figure out from there what needs to be done.

Sure, definitely make sure there's a reasonable structure that groups related styles together, but don't go overboard. Firebug makes things so much easier to track that you don't have to worry about making a perfect css structure up front.

Solution 12 - Css

ITCSS

By Harry Roberts (CSS Wizardry)

Defines global namespace and cascade, and helps keep selectors specificity low.

Structure

The first two only apply if you are using a preprocessor.

  1. (Settings)
  2. (Tools)
  3. Generics
  4. Elements
  5. Objects
  6. Components
  7. Trumps

Solution 13 - Css

Normally I do this:

  1. <link rel="stylesheet" href="css/style.css">

  2. In style.css I @import the following:

     @import url(colors.css);
     @import url(grid.css);
     @import url(custom.css); + some more files (if needed)
    
  3. In colors.css I @import the following (when using the CSS custom properties):

     @import url(root/variable.css);
    

Everything is in order and easy to get any part of code to edit. I'll be glad if it helps somehow.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam BellaireView Question on Stackoverflow
Solution 1 - CssmercatorView Answer on Stackoverflow
Solution 2 - CsswusherView Answer on Stackoverflow
Solution 3 - CssChris SpittlesView Answer on Stackoverflow
Solution 4 - CssOliView Answer on Stackoverflow
Solution 5 - CssNick SergeantView Answer on Stackoverflow
Solution 6 - CssJonathan ArkellView Answer on Stackoverflow
Solution 7 - CssShog9View Answer on Stackoverflow
Solution 8 - CsscllpseView Answer on Stackoverflow
Solution 9 - CssTim BookerView Answer on Stackoverflow
Solution 10 - CssallesklarView Answer on Stackoverflow
Solution 11 - CssSarhanisView Answer on Stackoverflow
Solution 12 - CssEric HarmsView Answer on Stackoverflow
Solution 13 - CsshtmlstrapView Answer on Stackoverflow