200
December 17, 2007Writing CSS Code: Inline and/or/vs. Block
A while ago there was a post by Steve Smith of Ordered List about how he formats his CSS on a single line per selector, brackets and attributes. I call this inline CSS. For the longest time I strictly adhered to a formatting quite the opposite, which I call block CSS. An example of both is shown in Figures 1 and 2.
- #example-div { width:400px; margin:0; padding:0; float:left; border:1px solid #999; background-color:#ddd; }
- #example-div
- {
- width:400px;
- margin:0;
- padding:0;
- float:left;
- border:1px solid #999;
- background-color:#ddd;
- }
I'm in the camp that would rather have a file with hundreds of lines than have to look through all of the attributes as they're formatted in Figure 1. However, there are some cases when block CSS seems a little overkill, such as Figure 3.
- #example-div a
- {
- text-decoration:none;
- }
I began to wonder if maybe I was being too strict with the block-only approach. Surely, it seemed, that the inline approach was more beneficial in some cases. Each had their benefits and liabilities, maybe I could combine the two for one harmonious style sheet?
At some point, I'm not exactly sure when, I did begin to mix the two and my CSS began to look more like what's shown in Figure 4.
- #example-div
- {
- width:400px;
- margin:0;
- padding:0;
- float:left;
- border:1px solid #999;
- background-color:#ddd;
- }
- #example-div a { text-decoration:none; }
Now as far as what determines whether the selector gets the block format or the inline format varies; there's no exact criteria, at least not yet. Generally, selectors with few properties will be written inline and those with more styling will get the block. I found that formatting CSS this way lends itself to an easy-to-follow rhythm as the style sheet grows (Figure 5).
- #example-div
- {
- width:400px;
- margin:0;
- padding:0;
- float:left;
- border:1px solid #999;
- background-color:#ddd;
- }
- #example-div a { text-decoration:none; }
- #example-div a:hover { background-color:#0f0; }
- ul#main-nav { list-style:none; border-top:1px solid #ddd; }
- ul#main-nav li { border-bottom:1px solid #ddd; }
- ul#main-nav a
- {
- width:150px;
- display:block;
- font-family:Georgia, "Times New Roman", serif;
- font-size:14px;
- color:#333;
- background-color:#eee;
- }
- ul#main-nav a:hover { color:#f00; background-color:#fff; }
Next up:
<br />vs.
<br/>! (Just kidding)
