Mar 10 10

Class: Developing CSS Systems

Developing a website is a complex endeavor, and it’s important to have a plan from the very beginning. One of the most important rules for developing a useful CSS system is this:

Create general styles first and specific styles last.

Styling your website is like creating a pyramid: create a good set of general styles as a base, with styles becoming fewer and more specific as you go. If you neglect to style your basic things first, you’ll end up with lots more specific styles, like an inverted pyramid. Not a very structurally sound prospect.

Why? Planning your styles in this way takes advantage of CSS’s concepts of inheritance and specificity.

  • Inheritance says that many of the styles applied to a parent item will be applied to it’s children as well. A familiar example of this is setting the font property on the <body> tag. All children of <body> will automatically inherit those font settings by default!
  • Specificity means that many styles can be applied to one object in different ways, and CSS will resolve conflicts by determining which one is more important. For example, I could apply a margin of 17px to all paragraphs, and additionally add color: blue; margin-left: 32px; to one of the paragraphs via a class. Can you guess what will happen? The browser will Make that paragraph blue and make all of its margins 17px, except for the left margin, which will be 32px.

What does this mean in practice? Put styles applied to tags toward the top of your css file. More specific styles for classes should go below that, and super-specific styles for IDs should go toward the bottom.

body {
   ...
}
a {
   ...
}
p {
   ...
}
.some-class {
   ...
}
#some-id {
   ...
}

Would you like to see an example of these principles? Download choose-your-own-adventure-example.zip. It’s a simple example of a website implementing these ideas.