Obsessive CSS Code Formatting: Opening and Closing Brackets

Post #535 categorized as Presentation, last updated on Apr 23, 2008
Tagged with css, Presentation, streamline, tips

Following my recent post on CSS code formatting, I was delightfully surprised to have received such insightful, enthusiastic feedback. Apparently, I am not the only person passionate about the subtle nuances involved with the formatting of CSS code. So, to continue the conversation, let’s explore several techniques for writing the opening and closing brackets of CSS declaration blocks.

Formatting method #1

I have seen this method used more than any other. The opening bracket appears on the same line as the selector and the closing bracket appears on its own line after the final property:

div#example_01 {
	padding: 3px;
	margin: 33px;
	width: 333px;
}
div#example_02 {
	padding: 3px;
	margin: 33px;
	width: 333px;
}
div#example_03 {
	padding: 3px;
	margin: 33px;
	width: 333px;
}

Standard stuff, maybe even a bit boring..? I don’t know. I tend to use this formatting method by default, although my technique is rapidly evolving to include a more sophisticated approach..

Formatting method #2

Recently I have been dabbling with this sexy little method. I love the way the closing bracket aligns neatly with the preceding declaration block:

div#example_01 {
	padding: 3px;
	margin: 33px;
	width: 333px;
	}
div#example_02 {
	padding: 3px;
	margin: 33px;
	width: 333px;
	}
div#example_03 {
	padding: 3px;
	margin: 33px;
	width: 333px;
	}

Of course, the major advantage to this technique is the improved readability of the various selectors. With no closing brackets cluttering things up, Locating target code is about as easy as it gets..

Formatting method #3

Although I have never used this method, I can certainly understand why people continue to use it. Every now and then, I will encounter a snippet of CSS that places the opening bracket on the line immediately beneath the selector:

div#example_01 
{
	padding: 3px;
	margin: 33px;
	width: 333px;
}
div#example_02 
{
	padding: 3px;
	margin: 33px;
	width: 333px;
}
div#example_03 
{
	padding: 3px;
	margin: 33px;
	width: 333px;
}

I think the idea here is to facilitate the readability of the code, however there is something that just seems out of place with that opening bracket. On a positive note, the uniformity of the bracket placement increases overall consistency and brings additional order to the document.

Formatting method #4

Last and quite possibly least, is the infamous “single-line” technique! For the more practical-minded folk out there, this method easily trumps the others with its sheer efficiency:

div#example_01 { padding: 3px; margin: 33px; width: 333px; }
div#example_02 { padding: 3px; margin: 33px; width: 333px; }
div#example_03 { padding: 3px; margin: 33px; width: 333px; }

Sure, this method looks great here, with the deliberately identical example declarations, but out in the wild, stylesheets employing the ‘ol single-line approach appear convoluted, complicated, and crowded. Yet, to those looking to squeeze that extra 5Kb out of their total bandwidth, the benefits of this technique are clear.

Share your thoughts

What is your preferred method for writing CSS brackets? Do you use one of the above methods, or something else? Share your thoughts!

Subscribe to Perishable Press


39 Responses

TopLeave a comment

[ Gravatar Icon ]

#1Gabe

I’m a deviation of “option #1″. I put the opening bracket on the line of the selector, but I don’t have any white space between said bracket and the selector.

[ Gravatar Icon ]

#2Perishable

What? No white space before the bracket? What about a blank space between the various properties and their values, for example:

padding: 33px;

..or do you write:

padding:33px;

and why?

[ Gravatar Icon ]

#3Lee

I use method 3.

I’m a developer (C# currently) and my code is formatted like that as well. In code you have a lot of nested sections so lining up the braces of each indented section helps make things easier to read.

So when I started creating stylesheets, I just used that method naturally since it mirrored what I was doing in code.

I agree that method 1 is most common in the wild.

For what it’s worth, I’m not a big fan of method 2. Probably because it’s so different from method 3. I’m accustomed to scanning the left side of a section for brackets - with method 2, I see nothing on the left side!

[ Gravatar Icon ]

#4chuck

ive been using method #2 for the last month or so and love it. works great with indenting children selectors and quickly finding the code.

before that i was a #1 guy.

[ Gravatar Icon ]

#5Perishable

My CSS formatting preferences have changed and continue to do so. For the first couple of years, I was also a #1 man to the core. Then, as my style evolved, I began to lean toward the second method, and currently choose it whenever possible. Given that trend, I would not be surprised to see my bracketing preferences change yet again at some point in the future. Oddly enough, I think the next logical evolutionary step would be #3, as it further facilitates easy reading (or so it seems). Bottom line? It may all be a matter of sheer practicality after all!

[ Gravatar Icon ]

#6Gyrus

I used to think #4 was insane, but now it’s how I do all my CSS. I find it much more “readable” in the sense that scrolling vertically through CSS files formatted using #1, #2 or #3 - even when you’re pretty good as efficient use of selectors etc. - can be a bewildering experience, to flip from one section to another.

After a little while a doing this for the above benefit, I found it very easy to read horizontally like this.

I try to keep block-level rules near the start and inline rules towards the end. And I use that logic as far as I can, e.g. float goes before margin as it seems more general and less specific.

Past that, #1 makes most sense. I always format braces like that, e.g. in JS functions. When if/elses and loops are nested, I find this style much easier to scan for matching.

[ Gravatar Icon ]

#7Louis

I think the formatting in this case is only a matter of taste. I personaly find myself very comfortable with the following syntax.

div#example_01{
padding: 3px;
margin: 33px;
width: 333px;
}

div#example_02{
padding: 3px;
margin: 33px;
width: 333px;
}

div#example_03{
padding: 3px;
margin: 33px;
width: 333px;
}

Yes, no indenting of the properties, and spaces between “blocks”.

Though, I’m a little disturbed by this sentence — speaking about the Formatting method #4.

Yet, to those looking to squeeze that extra 5Kb out of their total bandwidth, the benefits of this technique are clear.

I think that on the production side, you should always serve compacted & compressed content, because performance has such an impact on the visitor experience.

[ Gravatar Icon ]

#8Perishable

@Gyrus: I agree that single-line CSS blocks are an excellent way to save space. I often “punctuate” certain regions of method-#2-formatted code with single-line blocks, especially for single-property declarations. I also use single lines when identical/similar blocks of code appear sequentially, for example:

h1 { font-size: 3.0em; }
h2 { font-size: 2.0em; }
h3 { font-size: 1.7em; }
h4 { font-size: 1.3em; }

..or:

#g1 { background: url(g1_.jpg) no-repeat center center; }
#g2 { background: url(g2_.jpg) no-repeat center center; }
#g3 { background: url(g3_.jpg) no-repeat center center; }
#g4 { background: url(g4_.jpg) no-repeat center center; }

..and then continue above and below such lines with #1 or #2 formatting. To me, including regions of single-line code in this manner improves the overall flow and readability of the document. And of course, single-spacing between each segment (as shown in the example) is a must! ;)

[ Gravatar Icon ]

#9Perishable

@Louis: yes indeed, that is another fine example. Speaking strictly about opening and closing brackets, your technique seems like a modification of the first, most popular method. The opening bracket is on the same line as the selector (sans space), and the closing bracket is placed after the last declaration block, aligned with the first character of the selector. The fact that you don’t indent the declaration blocks themselves is also quite remarkable. Personally, I would find it difficult to locate the various selectors while scanning the document, but if it works well for you, then so be it! ;)

As for serving compressed and optimized code whenever possible, I wholeheartedly agree. I guess the point I was trying to make is that compression may not be necessary when writing CSS code in strict, single-line fashion. These documents are already relatively optimized such that further reduction in file size may prove negligible.

[ Gravatar Icon ]

#10Ben

I use method 4, with the added difference of no spaces after the colon. Removing this unnecessary space makes the individual parameters easier to locate.

For me the main issue is finding the class/ID, not finding the parameter within each one.

Out of the first 3, method 2 would be my choice. But the problem with all these for me is the sheer amount of scrolling involved in a large site’s CSS file. With method 4 you’re looking at only 2-4 screen heights max.

[ Gravatar Icon ]

#11Perishable

Looks like the fourth (single-line) method is more common than I had previously thought. Ben makes a good point about the readability of the code using this technique: locating the selectors is generally more important than jumping immediately to some specific declaration block. With the single-line approach, the selectors are generally neatly aligned to the left side of the screen, thereby facilitating their recognition. I have also seen CSS code using the single-line technique whereby reading is made even easier via skipped lines between code blocks and indentation of various subordinate blocks.

[ Gravatar Icon ]

#12Jordan

Method one all the way for me, with a space between the selector and opening brace. This is probably because it’s how I use curly braces in programming, so it just looks natural.

Recalling how you organize your CSS properties, I can see one reason you might prefer method two: visually, it would continue the wavy diagonal line along the right edge of your declaration block. What do you think?

Method three is the way one of my housemates formats all his code, including CSS. I don’t really like it, though… For some reason, it gives me the feeling that my code is slipping down the document like raindrops on a car window! However, the code is eminently readable, so it’s a defensible technique.

The fourth method is fine for single-property declarations or compressing files for the browser, but simply impossible for code that anyone else is ever meant to read! (Incidentally, when I do want to compress a stylesheet, I usually strip out all unnecessary whitespace, including any space preceding or following braces, colons and semicolons.)

[ Gravatar Icon ]

#13Perishable

Hi Jordan :)

Absolutely correct about your second point — that is precisely the reason I find the second formatting method so appealing. And, to continue along that same line of reasoning, method-2 brackets increase uniformity throughout the document by lining up with the left-most characters specified in the declaration blocks. The funny thing is, I had not been able to elucidate my preference for this method until reading about it in your comment. Thanks! ;)

I totally agree about the third technique, although a potentially useful formatting method, something about it just looks broken. I am so familiar with seeing the opening brackets of CSS code placed on the same line as the selector, that it almost looks ridiculous to see them placed on the next line. But again, it is a sound technique that may prove beneficial in the future.

As for method four, again, all great points. Although I employ single-line code blocks every now and then (as punctuation, for similar blocks, etc.), I find it impossible to design even moderately sized websites using this technique. By the way, I would be very interested in knowing which CSS compressor/optimizer you use to strip out all of the unnecessary elements in your CSS documents..

[ Gravatar Icon ]

#14Louis

The best compressor I’ve found that strip all the unnecessary spaces and co, is… your code editor. Just search and replace all “, ” with “,” for example, and so on.

You can also use YUI Compressor, it’s the best JS/CSS compressor out there in my opinion, and it has this really cool feature of letting you decide the max lenght of lines (one lined css file may have an impact on the CPU, and are a pain to edit.

It also does character encoding, which is great. UTF-8 FTW!

[ Gravatar Icon ]

#15Perishable

Yes of course! The humble code editor would indeed do the job (it may take a little longer, but hey, whatever!).. in fact, I use various text/code editors to do this sort of “find and replace” all the time, just never occurred to me to use this method to optimize an entire CSS file. In any case, thanks for the tips, especially for YUI compressor; I will definitely be checking it out (for both CSS and JavaScript).

UTF-8 — WOOT!!

[ Gravatar Icon ]

#16Kepler Gelotte

I am a programmer as well and use formatting method #3 for a few reasons:

1) It makes it painfully obvious when you forgot an opening/closing bracket. I have spent too many hours debugging code only to find my “if” statement didn’t have a curly brace at the end (That was in C code not CSS).

2) I use vi, so the ]] and [[ character sequences will jump to the next and previous open curly brace (begin block) only if it is the first character of the line.

Finally I compress and gzip my CSS using some apache/PHP code I wrote. This code compresses without my having to modify how I write my CSS. You can download it for free at http://www.coolphptools.com/dynamic_css

[ Gravatar Icon ]

#17Perishable

Wow, looks like #3 is winning by a landslide, apparently due to its sheer practicality (not surprising, given our money-mad market-driven economy). As you say, placing brackets on their own line makes it virtually impossible to forget or misplace them, especially when using a facilitative editor such as vi to expedite the process (note to self: check out vi). Some great points, Kepler, thanks for chiming in, and thanks for sharing your dynamic CSS compressor. I have downloaded it and will definitely be giving it a spin! ;)

[ Gravatar Icon ]

#18Jordan

Robson’s CSS compressor gives me the best results. I’ve tested a few, and this one is simply merciless at squeezing out every unnecessary character. (It supports UTF-8, too.)

[ Gravatar Icon ]

#19Perishable

Thanks for the followup, Jordan. I have bookmarked Robson’s CSS Compressor and will definitely be taking it for a spin! Cheers ;)

[ Gravatar Icon ]

#20rmaksim

method #2 + indents for internal elements of the parent blocks

div#example_01 {
      padding: 3px;
      }
      div#example_01 p{
            margin: 33px;
            }
            div#example_01 p span{
                  width: 333px;
                  }
      div#example_01 div{
            padding: 3px;
            margin: 33px;
            width: 333px;
            }

div#example_02 {
      padding: 3px;
      margin: 33px;
      width: 333px;
      }

[ Gravatar Icon ]

#21Perishable

Excellent timing, rmaksim! I just posted a follow-up article covering CSS indentation and spacing. Check it out!

[ Gravatar Icon ]

#22Jeremy Johnson

I actually use a combination of #3 and #4. I use #3 if I have more than one class or ID that share the same styles or if a class/ID has more than 2 or three styles.

I use #4 if I have a group of similar classes/ID that belong to a group. For example if I have a sprite consisting of 4 images, I place them together in a group in the #4 method.

[ Gravatar Icon ]

#23Perishable

Absolutely! Grouping single-line code blocks (as in method #4) is an ideal way to consolidate otherwise expansive regions of CSS code, especially where nearly identical declaration blocks are concerned. A great way to keep things clean and organized. Thanks for sharing!

[ Gravatar Icon ]

#24Louis

I changed my coding habits recently, and I guess here is the place to speak about it.

I switched from this to the one-lined declarations. I realised that I was actually spending more time locating the selectors than writing code. This is bad, so I tried the one-lined syntax and found it really confortable.

Also, it makes the structure of the CSS file clearer, as you can see in this screenshot.

[ Gravatar Icon ]

#25Perishable

Yes, one thing I learned from this series of articles is that, when it comes to CSS, sheer practicality often trumps expressive style. I also employ the single-line approach within compressed/optimized stylesheets, but prefer not to code that way. For my personal sites, where it’s all about personal expression and creativity, I take great pleasure in writing code as if it were poetry, with each line, jot and tittle carrying an intrinsic significance that transcends literal functionality. Each block of code is a verse, each declaration is a sentence, and the punctuation speaks for itself..

[ Gravatar Icon ]

#26Louis

That’s pretty much Wordpress’ slogan :)

Though, as beautiful as coding can be, I think real (litteral) poetry is a big step further in terms of difficuly.

[ Gravatar Icon ]

#27SneakyWho_am_i

I’ve moved from method 3 to method 4, and I fall back on method 2 for long lines. No tabs, though because when I jump on my Windows/Linux box at work/home, everything looks a bit weird.

[ Gravatar Icon ]

#28Jeff Starr

Good point about differences in code appearance from one platform to the next. There is also a great variety in how the code is displayed in different software applications. For example, I think Dreamweaver displays CSS very well, but I also enjoy working directly in notepad, which displays everything in monospace black and white text with no formatting whatsoever. For large stylesheets, I prefer Coda, Dreamweaver, or the like; but for smaller files and simple editing, notepad is perfect for me: crisp, clean, no-frills coding goodness. ;)

[ Gravatar Icon ]

#29Thomas Ingram

I’m actually favoring a variation on the first format:

.content_primary {
       background-color: #ff9966;
       }
       .content_primary p,
       .content_primary a {
                     color: #006699;
                     }
/* ... */

The idea is to indent items to show the inheritance hierarchy. Also each identifier gets it’s own line. This method works very well for me to not have to work out what applies to what. And it makes it very easy to override specific items if I wish. On the downside the extra tabs do add a little bit of page weight. But even then it wouldn’t be difficult to whip up a script to compress the CSS after you roll out your site.

While I’m here, I also have been separating different properties into individual files. That is, all color declarations in one file, all typography styles in another et cetera. Then I wrote a simple script to include only the styles I need in one download. It didn’t take too long, and I love how compartmented my code is. Everything in its place.

Sorry for going long. I probably should have put this on my own site and linked to it.

[ Gravatar Icon ]

#30Jeff Starr

Hi Thomas, excellent technique that I have recently adopted. Generally, multiple selectors do get their own line, although certain groups of selectors work just as well sharing the same line. I am finding that this “subordinate indentation” method works very well at keeping things organized, but it does take a little practice to get used to at first.

Using different CSS files for different types of styles is another useful organizational tool, although I don’t employ the method myself. As a performance optimization freak, I prefer to keep the number of server requests down to a minimum by keeping styles consolidated into one sheet per media type (i.e., one file for screen media, one for mobile styles, one for IE, etc.).

Great comment, btw — thanks for taking the time to share your technique! :)

[ Gravatar Icon ]

#31Mark

I favour this, which I also use for my C# (sadly no longer, Microsoft have now decided that I can no longer format the code how I LIKE to read it and after one update to my VS 2008 it now formats my C# like method #1 - yes I know its C# not CSS but I do think that formatting for whatever language should be left to coders and not the corporations!!!)

div#example_01
       {
       padding: 3px;
       margin: 33px;
       width: 333px;
       }

div#example_02
       {
       padding: 3px;
       margin: 33px;
       width: 333px;
       }

div#example_03
       {
       padding: 3px;
       margin: 33px;
       width: 333px;
       }

[ Gravatar Icon ]

#32Jordan

Just on the topic of Visual Studio’s so-called “smart” indentation: I would just like to rant a little about the bizarre, inconsistent, untidy and utterly unreadable indentation it enforces on inline VB code, essential when using the new MVC framework. It will happy increase the indention by twelve tabs from the last line for no good reason, and is apparently impossible to turn off.

I’m honestly about to hit my computer with a hammer. IDE developers, take note: programmers know what sort of indention rules they prefer, and what is most readable in a given situation. Provide some good defaults, by all means, but make them overridable or configurable—don’t just enforce your broken algorithms unilaterally.

[ Gravatar Icon ]

#33Dave Doolin

Tabs suck.

[ Gravatar Icon ]

#34Jeff Starr

@Dave Doolin: I disagree — I find them extremely useful. To each his own!

[ Gravatar Icon ]

#35Dave Doolin

@Jeff… yeah, I should have a j/k on that. I don’t like tabs myself at all, but I know I’m in the minority! I mostly suffer in silence…

[ Gravatar Icon ]

#36PragmaTechie

I haven’t really used this but just to make your list complete ;) :

Selector
          {
          attr:val;
          attr:val;
}

Personally, I find 2 (method 2 of your post ) needs lesser keystrokes but method 1 is quicker even with more keystrokes. How’s that? You use adjacent keys subsequently and double-tap the Enter key. Here’s what I mean:

1 type the selector and a space;
2 press Shift and { }; (though this is 2 characters, it’s quick and you need to press Shift only once)
3 press <–, double tap Enter, <– again; (this is really a quick sequence since the Left Arrow and the Enter key are close to each other and you press Enter twice)
4 press Tab and type your declarations;
5 press Down Arrow and Enter;

you’re now ready for the next rule!

Method 3 is just as quick as 1. Instead of a space in step 1 above, you press Enter. But observing the motion of my hands, I still think 1 is quicker because my thumb is already resting on the Spacebar.

I think that if you write a rule sequentially (char by char), 2 is the quickest as it needs the least keystrokes but if you group the same keys and adjacent keys, 1 is quicker.

But sometimes, you spend a lot of time thinking about the declarations that any speed gain using this method would be negligible.

Just a beginner’s thoughts, no big deal. If I happen to be wrong, just ignore this. :)

[ Gravatar Icon ]

#3730YearDev

@Mark #31

Cannot believe this format (basically Whitesmith) was not mentioned earlier. This is easily the best bracing format that exists - for virtually all curly-brace languages, including C, C++, Java, PHP, etc.

Think about it from a usability/readability stance - of course matched braces need to align with each other. But they do NOT need to be floating out in the left margins, hogging up your attention that should be focused on the actual control structure and content!

Beyond that, it’s a much better match for the actual grammer of these languages. The braces are part of the statement inside the control, NOT part of the control ! i.e. the definition of an if statement is:
if ( condition )
statement;

it’s NOT
if ( condition )
{ statements };

The grammer of a statement block is: ::= { ? }
For more details, see any BNF description, such as: http://www.daimi.au.dk/dRegAut/JavaBNF.html

In the first case, virtually everyone would agree that the inner statement MUST be indented.

The inner statement can be a single statement, or one or more statements surrounded by { }. And in either case, the statement or statement block should be consistently indented from the “if” itself. This leads to more readable code as well as being more “properly” structured, from a language point of view.

If you think it’s odd, just try it. I guarantee that unless you’ve closed your mind to advancement you will find that it’s by far the easiest formatting to work with — once you’ve flushed the other garbage out of your head. Granted, this can be hard to do if you’re in a shop with poor code formatting standards, but you can try.

Share your thoughts..

TopRead official comment policy

The rules are simple. Comment intelligently. Stay on-topic. Don’t spam! Suspected spam will be deleted. Use your real name or nickname, not a site name or business name. Using a site name or business name is a good way to get your link or comment removed. Certain comments are moderated; if your comment does not appear after several days, or if you wish to comment privately, contact me. Also, by posting a comment, you grant this site a perpetual license to reproduce your comment, name, and website URL. Lastly, you may use basic HTML markup, but please do not use <pre> tags. Instead, wrap your code with <code> tags. Use a new set of <code> tags for each code term or phrase, as well as for each individual line of code (i.e., multiple lines of code require multiple code tags). Please see the complete comment policy for more information.