Jun 22 '08
How To Write Modular CSS, Round 1: The Preparation
Welcome to the first installment of How To Write Modular CSS. In this round, we’re going to cover what’s probably the most important piece of this entire discussion: preparation.
As with just about everything in life, designing and coding for the web is wrought with multiple methodologies — some good, most bad. This of course is my interpretation of the most useful methods, but while its based on a lot of experience, I am certain there are better ways and potentially even errors and a lot of it will be recycled information. The goal is here though is less to be revolutionary, and more to teach efficiency, productivity, and method. Most of all, I hope you’ll tear down everything you find here, rewrite it, talk to me about it if you think it’s crap, or ask questions if you don’t understand. Better code is bred from collaboration and reinvention.
So what are we “preparing” for exactly? Well, it’s a bit of geek calisthenics, but mostly we’re laying a foundation upon which we can build freely and without concern. At the risk of oversimplifying, here’s a quick checklist to use that will ensure you have clean and useful code on which to build:
- Use A Reset
- Comment, Comment, Comment (And Structure)
- Inline Or Multiline… But Be Consistent
- Proper Naming Conventions
- Organize Your Attributes
Use A Reset
This is the easiest thing in the world, and yet I see site after site struggling with silly visual inconsistencies that can be easily squashed by starting with a reset foundation. I’m not going to get into exactly what a reset does right now, but suffice it to say it evens the playing field across browsers (as best as possible). I know a pretty good one you can use to get started (wink wink), which is of course based partly off the work of Eric Meyer, the Blueprint framework, et al. This will save you tons of code, and tons of heartache.
Comment, Comment, Comment (And Structure)
Again, this should be a no-brainer, and yet I see more sites than I care to think of that line after line of code with nary a comment in sight and no apparent structure. So here are two strong recommendations for commenting and structuring your CSS properly:
- Create a core set of items you define once (think of it as an extension of your reset). This includes all the basic typographical elements and core layout structures of your pages — things like p, a, a:hover, h1, h2, ul, li, em, as well as the main components of your page, which you’ll probably end up naming #wrapper or #sidebar or whatever you like. This way, you have all the basic presentational elements in one place so making wholesale edits to font styles or sizes or basic resizing of site elements is quick and painless. You might ask why these aren’t in the reset, and I will address that later on in the series as well. For now, the short answer is because the reset is really reserved for items that will be used in all sites, not just your specific site.
- Use easily identifiable comments to separate your stylesheet by pages, sections, or whatever makes sense to you. There’s a great article about this here so I wont spend a ton of time rehashing, but the essence of it is simple: put large comment headings in your stylesheet so you can easily scan and find sections. You can even use my structure if you like it:
/* ------------------------------------------------------ SECTION TITLE ------------------------------------------------------*/
The article above also makes note of what they call flags, which is really just putting an uncommon character (like an “=” sign) in front of your comment’s label so that you can jump between sections really easily using a Find command for “=”. It’s a very good idea, especially for very large style sheets, although I am guilty of ignoring or forgetting this one myself. The key though, is making it easy to scan your sheet, be it visually or via Search/Find. You also can (and should) include smaller comments on individual items to remind you about limitations of your structure, things you want to change or tweak, etc. But these comments don’t need to be quite so large or structured… more like margin notes you’d make in a book.
Inline Or Multi-Line… But Be Consistent!
This is a contentious point for some designers, and I of course have my opinion (inline all the way!). But, the main point here is whatever style you prefer, just be consistent.
In case you’re unaware, there are two ways to write the syntax defining the properties of most CSS elements. The multi-line method, or long-hand, is where you define each individual property on its own line, like so:
p {
margin-top: 0;
margin-right: 0;
margin-bottom: 1.4em;
margin-left: 0;
font-style: bold;
font-size: 1.2em;
line-height: 1.7em;
font-family: Helvetica, Arial, sans-serif;
color: #333333;
}
…whereas the inline, or short-hand, method, of the same exact CSS would appear like so:
p { margin: 0 0 1.4em 0; font: bold 1.2em/1.7em Helvetica, Arial, sans-serif; color: #333; }
I much prefer the second method because it really tightens up your stylesheet into far fewer lines, saves you some file size, and (more subjectively) it just feels more elegant to me. But whatever your preference, you can probably see that a stylesheet that is littered with both of these styles in different places can become illegible and confusing very quickly. So keep it clean, keep it organized, and keep it consistent.
Proper Naming Conventions
This has been written about by many people over the years. Most recently, I came across an article by Jina Bolton where she talks about this point (and much of what I’m writing in this first round as well actually). One of the best points she makes is in reference to naming conventions and how they relate to semantic markup. Her sample is a great example of how nondescript class names like .l13k are useless to anyone except the author, whereas more semantic names like .product-description are descriptive, helpful, and not tied to any display element like color, position, etc, that might later be changed. This is excellent advice, and you should take it to heart when naming your classes and ids.
Aside from general cleanliness of code, I also try to get people to be consistent with the syntax of their naming conventions because it become helpful when you get into more advanced coding. Again, there’s more than one way to skin a cat, but decide early on whether you like to use underscores or hyphens in multi-word class/id names, or if you prefer camel case (like myClassName). There are good arguments all around, and with the possible exception of the emergence of Microformats (which use hyphens) there really isn’t any tangible evidence that one is better than another. Again, the key is to pick something and be consistent with it or you’ll end up spending as much time scrolling around to get reacquainted with code you already wrote as you will writing new code.
Organize Your Attributes
This last bit appears really pedantic, and I suppose it might be on some level. But, organizing your attributes can be a really useful and time-saving technique that will help you easily scan styles. More importantly though, organizing helps keep things consistent will lead to you writing more efficient and reliable code.
So what does it mean to “organize your attributes” … sounds kinda kinky, eh? Well, attributes are the actual values you define for a particular class, tag, or whatever you’re working on… things like height, padding, font-size, etc. So when I say “organize your attributes”, I’m referring literally to the order in which they appear. This doesn’t have to be a 100% perfect science — that would surely be pedantic — but as a rule, keeping things in close to the same order all the time will help your speed and accuracy tremendously. For me, the most sensical order is to work from the outside in as it pertains to the box model (we’ll cover the box model later too… for now, look it up). That means, float and display mode attributes first, then spacing attributes, then font styles, and finally backgrounds and borders (yea, I know, background and borders would be before fonts and colors… but I like them at the end). So, if it helps to see it visually, below are the most common attributes, spread out in the order they will always appear in my stylesheets:
.my-class {
float
display
height
width
margin
padding
font
color
border
background
}
Class Dismissed… For Now
And so that’s the crux of our foundation. This stuff, as the title might suggest, is far more preparatory and utilitarian, but it is potentially the most important part of writing strong code. If your foundation is strong, you can always get better at the ins and outs of more complex layout. But if you start with a weak frame, your pages are destined to break.
Next time, we’ll pick up with talking about what constitutes truly “semantic” code (buzz word alert) and why its so important to making your CSS solid and modular.
4 comments
Thanks so much for this. It promises to be most helpful for me. I am a designer, screen based & animator who has never had to touch code, HTML, I know a little actionscript but that’s it. I’m a photoshop mock-up designer. I’v been doing it for years & have resisted everything to do with development. It has come to the point where I feel I have to learn this stuff to keep up, & know exactly what is possible. I can not rely on coders any longer. Some are good, some aren’t. I want to know from experience if something’s possible. It’s become a steep learning curve, made even steeper thanks to my lack of patience. Thanks to learning from people like you, who have gone thru alot of the trials & tribs before, I think it will save me a great deal of pain. Please keep these lessons & words of wisdom coming ASAP. Thaank you!
@Matt - You’re very welcome… glad you found it helpful! More is on the way.
[...] How To Write Modular CSS Balcom&Nobody goes into detail on how to write modular CSS from the reset to proper naming [...]
I’m surprised no one talks about the listing css in the external stylesheet alphabetically. I’d go bonkers if my css was just random.