CSS: Simple Rules for Better Organization and More Efficiency
Published on May 15, 2008 (⻠July 11, 2024), filed under Development (RSS feed for all categories).
This and many other posts are also available as a pretty, well-behaved ebook: On Web Development. If the optimization of CSS is of particular import to you, Iâve collected several concepts in a brief book: CSS Optimization Basics.
âOrganization is not everything, but without organization, everything is nothing,â one of my teachers used to say. Almost everything benefits from organization, and so does work with CSSâespecially when working with many people. During the years I took special care of organizational standards for HTML and CSS (German readers might know the coding guidelines I created for GMX and Aperto), and there are plenty of âproofs of concept.â
Then, over time I refined my personal CSS coding guidelines. Here I want to share three basic rules I use for consistent organization and improved efficiency (which, by the way, is what I referred to when announcing CS4 in January).
Sort and Group by Selectors
Web developers taking the modular approach tend to do this already, but for everyone itâs worthwhile to standardize selector order, both for yourself and for the team involved. In my projects I currently use the following order (although not including all elements):
*, html, body, h1, h2, h3, h4, h5, h6, p, address, blockquote, pre, ul, ol, li, dl, dt, dd, table, caption, tr, th, td, form, fieldset, legend, label, input, textarea, div, img, a, strong, em, abbr, q, cite, code, kbd, var, span, #id, .class
This sorting method works both âhorizontallyâ and âverticallyâ:
ul, li, .note {}
ul {}
li {}
.note {}
The rule gets slightly more complex when including descendant selectors; I like to apply the same order (e.g. p em, p abbr {}
), but let simpler selectors go first (p, p em, p abbr {}
). Another subrule worth mentioning is the order applied to selectors, like p
and p.warning
, where it would be p, p.warning
(or p, .warning
, fitting the above scheme again), both horizontally and vertically, too.
This is a rather rough description of what I use and with what I had good experience. Use it as the foundation; for instance, you might opt for a âmodule-centricâ approach by applying this order within CSS sections like navigation styles rather than whole style sheets.
Update (February 14, 2013)
I published a comprehensive draft to order CSS selectors.
Use Any Declaration Just Once
Exactly: Use any declaration just once. The reason for that is that on average, declarations are longer and thus add more weight to style sheets than selectors (and selector groups), and thus take more time to load. Another reason is that âUDJOâ reduces the need for CSS variables (not: selector variables)âin many cases you donât need them at all.
Letâs see a short but realistic example:
h1, h2, h3 { font-weight: normal; }
a strong { font-weight: normal !important; } /* exemplary, take it as given */
strong { font-style: italic; font-weight: normal; }
#nav { font-style: italic; }
.note { font-style: italic; }
Applying the âany declaration just onceâ rule results in
h1, h2, h3, strong { font-weight: normal; }
a strong { font-weight: normal !important; }
strong, #nav, .note { font-style: italic; }
This saves a few characters (and load time) without getting into the way of maintenance.
Note:
-
Overly long selectors can drive this method useless. Repeating selectors like
html body table tbody tr td p span.extraordinary-class-name
in order to have unique declarations doesnât save muchâit might instead be a signal to use more compact selectors. -
Be aware of CSS constraints: When a user agent canât parse a selector, it must ignore the declaration block as well. If you run into trouble with this because of, say, hacks, just bend the rule accordingly, i.e. use the declaration in question twice.
-
Keep the cascade in mind when using this rule in conjunction with the sorting one.
-
This organization and efficiency rule requires more attention when maintaining style sheets. Find a way to track changed and added declarations in order to keep them used only once, tooâthis is not hard when using a more or less reasonable editor (showing line changes, for example), but needs to be incorporated into your workflow.
Update (October 26, 2017)
I published a comprehensive guide to use declarations just once.
Sort Declarations Alphabetically
There are I-donât-know-how-many ideas how to sort declarations within declaration blocks, but the simplest and âcognitively least demandingâ is alphabetical sorting. So instead of thinking measurements first, then colors, then dimensions, and so on, just order alphabetically:
#content {
border: 1px dashed;
color: #000;
margin: auto;
padding: 1em 0;
width: 700px;
}
I know that other sorting methods (or no sorting at all) have friends, too, but Iâm certain that this is the simplest and most straightforward one.
Example
Letâs use WHWSâs 2006 standard style sheet to apply all these tips to one style sheet:
@media screen, projection {
* { margin: 0; padding: 0; }
html { background: #000; color: #ccc; font: 87.5%/1.5 optima, arial, sans-serif; text-align: center; }
body { margin: 1em 0; }
h1, h2 { font-size: 1em; font-weight: normal; }
h1 { background: url(/media/logo.jpg) no-repeat; height: 366px; text-indent: -999em; width: 620px; }
h2, p { margin: 0 .5em; }
p + p { text-indent: 1em; }
p#ref { background: url(/media/end.jpg) no-repeat bottom center; margin: 1.5em 0 0; padding-bottom: 179px; }
ul { margin: .5em 0 .5em 1.5em; }
ul#lang { list-style: none; margin: .5em 0 1em 1.5em; }
ul#lang li { display: inline; }
div#show { margin: auto; text-align: left; width: 619px; }
div#whws { background: url(/media/tape.gif) repeat-y top center; margin: 42px 0; }
div#whws + div { position: relative; }
a, strong { color: #fff; }
strong { font-size: 1.3em; line-height: 1.0; }
kbd { font-family: optima, arial, sans-serif; }
}
⧠Ultimately, use whatâs best for you. If you feel inspired by these rules try them on for size in smaller projects.
About Me
Iâm Jens (long: Jens Oliver Meiert), and Iâm a web developer, manager, and author. Iâve worked as a technical lead and engineering manager for a few companies, Iâm a contributor to several web standards, and I write and review books for OâReilly and Frontend Dogma.
I love trying things, not only in web development and engineering management, but also in other areas like philosophy. Here on meiert.com I share some of my experiences and views. (I value you being critical, interpreting charitably, and giving feedback.)
Comments (Closed)
-
On May 16, 2008, 0:42 CEST, Duluoz said:
Great article as always Jens.
Choosing a great mono-spaced typeface also helps you be more efficient in working with any code. There are many typefaces created specifically for making code easier to read and comprehend quickly. Just like serifs help us read a newspaper or a book comfortably, so will a mono-spaced typeface help us see code more comfortably.
-
On May 16, 2008, 9:45 CEST, Jens Oliver Meiert said:
David, thank you. Concerning fonts for code, I intentionally take this approach in order to avoid the problem that the code font does not typographically fit the usual type. But this may change once I find a working alternative đ
-
On May 16, 2008, 11:19 CEST, Alan Gresley said:
I do believe the best way to learn organization in oneâs CSS is to have dis-order first and while you fixing this dis-order, youâll remember not to make the same mistakes again.
You can apply that to many things in life, even the development of the web.
-
On May 16, 2008, 16:00 CEST, Trevor Davis said:
I agree 100% about alphabetizing CSS properties. I started doing it about a year ago, and now I cannot imagine doing anything else.
It also helps a lot for consistency when you are working with a team of people.
-
On May 17, 2008, 3:36 CEST, Jens Nedal said:
I like the alphabetical order approach for declarations.
In our team we use a background ro foreground and outside to inside approach, looking at the box model.like
... { background: ... margin: ... padding: ... border: ... ... } ...
This suited us well since the boxmodel is something that is always in your head. Its more along the lines of your selector sorting and grouping. Not totally adhereing to the boxmodel order.
-
On May 19, 2008, 15:33 CEST, Alan Gresley said:
Jens, Iâd suspect there to be inconsistencies, or did you really have good experience with that approach, has there been enough âdisciplineâ?
I would go along with Jens Nedalâs approach but in a different order (seen in my CSS), like:
font-size: .. width: .. height: .. padding: .. margin: .. border: .. background: ..
Then repeated rulesets later in the cascade for progressive enhancement and hackery.
I almost always have background last since mine usually take up a whole line. đ
-
On May 20, 2008, 18:40 CEST, Duluoz said:
To be honest - I never gave a rats behind about the order of the selectors. I work with several other developers right now and we just throw any old selector anywhere (outside of how we want things to inherit obviously). I canât say that Iâve ever been âconfusedâ or misunderstood something because of the order.
You know the scene in the movie âThe Matrixâ where the guy is looking at all the code flying down the screen and he says he just learns to âsee the matrix, not the codeâ? Thats kind of how myself and anyone I know that deals with CSS everyday sees things. We see it all as a whole.
I think its a nice habit to have, donât get me wrong, I just never put much value in it.
-
On May 25, 2008, 1:53 CEST, Jordan Clark said:
Iâm another fan of alphabetizing CSS properties. It just makes sense, and helps to ensure that you never redeclare a property by accident.
However, thatâs not to say that I donât make the odd exception to this rule. For instance, with the
position
property, I like to keep the directional values (top
/right
/bottom
/left
) directly below it so that I can quickly work out whatâs happening, e.g.:.example { border: 1px solid; font-weight: bold; position: relative; top: 10px; left: 10px; width: 100px; }
(It makes sense to me, anyway!)
-
On July 2, 2008, 0:20 CEST, Tedel said:
I liked your article. My congratulations.
-
On October 10, 2008, 22:02 CEST, Joel said:
I just wrote a tool that converts single-line and multi-line css.
-
On July 9, 2009, 21:32 CEST, Jonny Axelsson said:
I follow a âMost important firstâ organisation of properties, starting with layout properties like ‘displayâ and ‘floatâ, generated content, box model, colour, typography, and aural properties.
The rationale is simple, it makes debugging easier, you can quickly scan to likely point of error. However it probably would fail with a large organisation and it depends on everyone having a good command of the entire CSS 2.1 vocabulary. With the much larger CSS3 vocabulary it would be considerably harder to maintain.
-
On December 25, 2009, 18:40 CET, Steffen said:
As far as I understand the grammar from the css specification
'{' S* declaration [ ';' S* declaration ]* '}' S*
or the verbal explanation (âsemicolon (;) separated groupsâ) the trailing semicolon in the declaration block is not only unnecessary but also invalid.
I have to admit that I couldnât find the reason why the validator doesnât list it as an error though.
Come on Jens, save some more bytes and remove the semicolons for the sake of your never ending quest for speed đ -
On April 16, 2010, 16:50 CEST, Andre said:
Great contribution. Found it via smashing magazine
-
On May 5, 2010, 0:51 CEST, Henk said:
This: âUse any declaration just once so it takes less time to loadâ is a very good tip.
How do you sort your declarations alphabetically when you have grouped some of them?
Read More
Maybe of interest to you, too:
- Next: Less Is Still More
- Previous: Website Optimization Measures, Part IV
- More under Development
- More from 2008
- Most popular posts
Looking for a way to comment? Comments have been disabled, unfortunately.
Get a good look at web development? Try WebGlossary.infoâand The Web Development Glossary 3K. With explanations and definitions for thousands of terms of web development, web design, and related fields, building on Wikipedia as well as MDN Web Docs. Available at Apple Books, Kobo, Google Play Books, and Leanpub.