Regex Patterns for Single Line CSS

Update: You can now download the Textmate macro file rather than recording your own (skip to the download »).

There has been plenty of discussion about the pros and cons of single-line style sheets, and I’ve been including them as an option when teaching CSS management and organization in my Web Design World presentations in Chicago, Seattle, and later this year in Las Vegas (at WebBuilder) and Boston.

It’s a matter of preference

As a fellow Sidebar-ian (Sidebarbarian?) Steve has been trying to convince me to use the single-line approach for a while of course, and Bryan and Jon have also become fans of this formatting style for their own work. Although they are enamored with it, I haven’t taken to it yet, still preferring to write my style sheets using the “normal” indented formatting most of us are used to.

Now, before anyone gets their knickers in a twist about why they love, hate, “can’t live without” or “will die before they try” single-line formatting, let’s just take a step back and remember one thing: it isn’t anything special, just an alternate formatting style that doesn’t affect the way the browser interprets the style sheet one iota. It’s a personal preference—remember that before jumping on or off this particular bandwagon.

Always keep your options open

Now that I’ve got that out of my system, let’s talk practicality: there are indeed benefits to be had when using single-line CSS formatting—for example, I find it can make a difference after a project has been completed, at which point I’m usually more interested in visually scanning a style sheet for the selectors first, and then for a particular property I’m interested in editing. This is where I’ve found single-line formatting can come in handy.

But my editor already does that!

This is the point where some people will start going on about how you could just use Textmate’s “foldings” feature to get the same visual result (without altering your file), or how CSS Edit has a handy list of all the selectors in a column on the left side of its window, or that you could always use your editor’s “find” command and search for the selector you want to edit. Yet while those are all perfectly logical, sane suggestions, they don’t account for flexibility and choice.

Just another way of doing things

Much like Jon Hicks with his harem of web browsers, I tend to be a bit of a “text editor polygamist”, bouncing from Textmate to CSS Edit to Coda to BBEdit to Transmit’s text editor and a host of CLI editors, mostly depending on my mood (though sometimes contextual if I’m at a computer that doesn’t have a particular application—a WindowsXP box with nothing but Notepad, for instance). It’s the times when I’m using an editor that doesn’t have “foldings” or pretty columns of selectors that I start to appreciate single-line CSS when making quick edits, so I’ve started converting style sheets to a “simple” single-line format (without the left-aligned tab blocks to start each rule’s properties) once they are ready to go live.

Patterns fit for a kilt

Editors like Textmate and BBEdit have built-in commands for formatting (the standard, multi-line approach) or compressing (the entire style sheet on one line, ostensibly to reduce file size by stripping white space) CSS, but no way to convert to single-line formatting and Textmate’s “Format CSS Compressed” bundle can format your stylesheet to a single line per-rule, though it’s all squished together, making it difficult to scan due to a lack of whitespace. Converting a style sheet by hand every time would be much too time-consuming to bother with, but that’s where regular expressions come to the rescue.

In Textmate, you can record a macro using each of these regex patterns as a separate step (I’m sure other editors have a similar feature, so please feel free to post details in the comments below). This allowed me to create a “Format CSS Single-line” command, complete with a keyboard shortcut, which enables an easy switch between multi- and single-line formatting.

Unfortunately, as of this writing Textmate macros cannot be exported and shared For those using Textmate, getting the macro is a simple matter of downloading, expanding and double-clicking this file:

While similar to “Format CSS Compressed”, this macro retains a single blank line where your original contained two or more blank lines (helpful if you group your rules), and adds whitespace that matches my standard formatting preferences (which I find makes it easier to scan quickly). To switch between each formatting style, just run each command in turn (via the Bundles menu or the keyboard shortcuts).

However, that wouldn’t be much use to everyone who doesn’t use Textmate, so here are the respective groups of regex I used for the conversion:

\n{3,}
\n\n

[ \t]+
 
(?m)([;:])\s+
$1

\s*}
 }

\s*{\s*
 { 

[ \t]*,[ \t]*
,

@import(.*?);
@import$1;\n\n

What’s missing

In Textmate and BBEdit I can return to multi-line formatting with a single command, but that might not be as simple in other editors. What I’d love to see is a pair of shell scripts that convert from multi- to single-line and back, and possibly a web-based processor that does the same (paste your style sheet into a textarea, select your formatting, hit “process” and the script produces the result). If anyone would like to take on those tasks, I’ll happily update this post to link to the products of your labor.

And in the end…

If you’ve never tried single-line formatting, this makes it easy to experiment without committing yourself (and I do recommend giving it a try—you may be surprised once you’ve worked with it a few times).

Ultimately, because I can return to multi-line with a single command my primary text editor should I ever feel like it, automating the switch from multi- to single-line is a convenient way to get the benefits of single-line formatting without backing myself or my clients into a formatting corner.

Comments

67 responses to “Regex Patterns for Single Line CSS”

  1. Ian Avatar

    I’m a multi-line CSS coder myself but I totally understand why people like the single-line method. It does look cleaner and more organised and at first glance is easy to scan through. I’ve considered something similar in the past where it would be good to develop multi-line but then have something to convert to single line just before you put it live but keep the original multi-line file intact.

    I mainly use Coda as a text editor so I may try and see if I can get your regex method to work in that. If not then I’ll see how it turns out in TextMate.

    Definitely a good call though!

  2. Dan Avatar

    I can absolutely understand why people like the idea of scanning their style sheets faster, but from a time saving standpoint, I’d rather shut down my e-mail/IM programs for an hour and write indented style sheets.
    I feel that this obsession with saving time that every one seems to have, is borne out of their refusal to stop refreshing twitter every 5 minutes or getting distracted with rss feeds or e-mails.

    There are much better ways to save time working, that condensing your style sheets.

    But like I said, if you like it, and if you prefer it to indented sheets, thats fine, but I don’t think it stands on its own as a purely time-saving measure.

  3. Dan Rubin Avatar

    @Ian: I still prefer writing style sheets in multi-line, as I’m mostly focusing on properties while authoring. It’s when referring back 6 months later to a style sheet that single-line often comes in handy, since I’m a visual person and it makes scanning the selectors much easier.

    Something worth checking out is Shaun Inman’s CSS Cacheer, which pre-processes stylesheets on the server, leaving the original source untouched (though I’m not sure if that would help when *editing* CSS, which is when single-line works best for me).

  4. Dan Rubin Avatar

    @Dan: I don’t think you actually read my post, did you :)

    Aside from my rant about people arguing which formatting is better (which I think is silly and definitely a waste of time), I mention that I prefer working in multi-line, and I make no mention of single-line saving time during the development process—in fact, the entire point of the article is the regex that takes a split second to run, and only after writing all your styles with multi-line formatting to begin with.

    This isn’t meant to be a time-saving tip, but rather to make long stylesheets a bit easier to scan when diving into them well after they’ve been completed.

  5. Marcos Avatar
    Marcos

    I understand why the multiline approach is easier to read, but I prefer single-line to code.

    And I read in firebug, much much easier to find that line in the code.

    Find the selector visually in Firefox, see wich line firebug talks about, and go to the editor!

    Single-line makes it much easier to see the whole selector structure, be aware of specificity, visualy group similar selectors, etc

  6. Ian Avatar

    @Dan Rubin: Thanks for the tip on Shaun’s CSS Cacheer. For me personally it sounds like quite a good solution. I like writing and editing in multi-line because I like to quickly see and edit which the various properties of the selectors. Single-line (preferably indented) is good for a quick overview of the whole document to see how it’s all put together and handy when returning to work you haven’t touched in a while or someone else’s code. I’m sure it must have some loading time benefits too being much more compressed with less whitespace and line breaks. To have the original multi-line file to edit and a single-line file when live would be the best of both worlds.

    It looks a little confusing at first glance but I’ll give CSS Cacheer a try to see how it works out.

    Thanks.

  7. Dan Rubin Avatar

    Because this is a formatting post more than anything, it’s worth noting that there are probably improvements that could be made to the series of regular expressions I posted. I can imagine someone out there could figure out how to compare all the selectors and indent similar ones, or measure the longest selector length and then calculate the number of tabs needed for each line to have a uniform left-alignment for all the declaration blocks (which is how many folks format when they code single-line by default).

    It’s all about options people—what works best for one person might be awful for another, we can’t assume that one approach works best for all people.

  8. Riddle Avatar

    Dan, what about editing properties and combining rulesets? Do you prefer overwriting properties with more CSS or do you optimize it as tight as you can?

    I prefer the second approach and I tend to think it’s better. It saves fellow developers from looking at clutter and is decreases the time is takes to load such CSS file.

  9. Dan Rubin Avatar

    @Riddle: I tend to prefer optimizing when there are logically inherited or shared properties, but there are many cases when I’ll use separate selectors and repeat the properties if I think there’s a reason for including the hook to adjust it in the future.

    When clients will be editing the CSS once a project is finished, sometimes overzealous optimization of rules can make it very difficult for a non-expert to understand what they’re looking at. Being a bit more specific with the selectors, along with commenting style sheets, can go a long way toward making it easier for other people to edit and maintain those styles.

  10. Riddle Avatar

    Yes, I know it’s a matter of preference, but if someone skips optimization and leaves duplicates in his/her rules then it’s a different thing, isn’t it?

  11. Dan Rubin Avatar

    @Riddle: I’d tend to agree with you on that point: if I have a duplicate property, it’s intentional and serves a purpose. If someone leaves their style sheet in an unoptimized state, and doesn’t even attempt to remove unnecessary duplicate properties, then that falls on the lazy side.

    Of course, in the real world when facing tight production schedules, things get overlooked and duplicates exist. And that’s okay.

  12. David VanDusen Avatar

    It’s in the works:

    CSS Compress

    It removes comments (which I could add as an option, I guess) and strips whitespace (also an option, maybe.) You end up with a neat little css file with no superfluous space other than a newline at the end of each rule set.

  13. Louis Avatar

    You should have a look at the series of articles at PerishablePress. Here’s the last one : http://perishablepress.com/press/2008/07/05/obsessive-css-code-formatting-organization-comments-and-signatures/

  14. Dan Rubin Avatar

    @David: That’s a good start—having options for comment removal and handling of white space would be very useful, again because a lot of these things come down to personal preference.

    @Louis: That’s some obsessive-compulsive CSS commenting in that article! I’m a big fan of using comments to organize stylesheets, but there are some great examples there of how comments can be taken seriously far :)

  15. David VanDusen Avatar

    I’m not sure I want this to become a pet project, but I added those options.

    It occurs to me that in order to pull this CSS formatting thing off correctly, (with options et al,) a more complex parsing of the CSS needs to take place. Beyond using regular expressions to search and replace for strings in CSS code, a parser would create an object from the code and regenerate it with the appropriate formatting.

    However, for situations like preparing your CSS for publication, compressing it to single-line formatting or a blob will do fine.

  16. Dan Rubin Avatar

    @David: Slap a logo and a few styles on that puppy and it’s ready for prime-time! :) As you said, for the basic needs a form like this needs to fill, it doesn’t have to be complicated. Tools like Conditional CSS and Shaun’s CSS Cacheer (linked above) provide other, more dynamic ways to mess with your CSS, so it’s nice to have a few simple options too.

  17. Michael Sheets Avatar
    Michael Sheets

    You can share this macro quite easily, just open the bundle editor and drag the macro to the desktop. You’ll have a file you can post and people can double-click it to install.

  18. Dan Rubin Avatar

    @Michael: Is that new? I’d checked the documentation a few months ago and it wasn’t possible (it’s been a while since I created this macro). I’ll give it a shot and update the post with the file download…

  19. Ben Avatar
    Ben

    Sharing bundles has been a feature since at least 2006, when I started using TextMate.

    I don’t know if the behavior where you can drag an item to the desktop is new, but you’ve always been able to go to:

    ~/Library/Application Support/TextMate/Bundles

    And grab any customized bundle from there.

  20. Dan Rubin Avatar

    @Ben: I’ve used Textmate since the beginning, and was aware of sharing bundles, but I could have sworn I read somewhere in the documentation that macros couldn’t be shared… as it turns out, after searching through the docs for that line, I think I was just remembering incorrectly the reference to macros not being editable (still in the Help docs in the current version).

    I’m of course happy to be wrong, and will be uploading the file as soon as I have a spare moment (on vacation atm, difficult to steal even enough time to check for and reply to comments :)

  21. Dan Rubin Avatar

    Anyone who’s read this far but missed my update to the post: The Textmate macro is now available to download »

  22. Dmitry Baranovskiy Avatar

    I am personally use multiline stylesheets, BUT if I want quickly rush throughout the file I simply press ??0 in TextMate. Search by symbol (??T) also works pretty good.
    I was playing with macros before and even created one which also alphabetise properties, but then I just found that TextMate is smarter then me :D

  23. Nater Kane Avatar

    in addition to the link @David shared, there’s also this.

    cssdrive’s version has a few other options when it comes to stripping certain types of comments (to leave in a few hacks folks still make use on occasion) as well as light, normal and super-compact modes for whitespace stripping.

    i usually deliver two copies of any style docs with any project (similar to dev and compressed versions of .js files). on large projects, simply removing line breaks can sometimes save 1-2k.

  24. […] not forget! For those out there working on Textmate (or having access to it anyway), there’s this great script from Dan Rubin that converts your single-lines to multi-lines in a sec, using the powers of […]

  25. magnao Avatar

    Read this post, got inspired, whipped this up:
    http://magnao.com/software/flat-css/
    All JS, all client-side.

    Note on combined rulesets: they’re a pain to deal with while developing, but are very useful in conserving space when in production. I use http://www.cssoptimiser.com/ for my CSS optimization.

  26. Dan Rubin Avatar

    @Nater: Thanks for the additional link! It’s nice to have options :)

    @Magnao: Now that’s pretty cool! Maybe put it on a domain by itself? Either way, I’ll add it to the list of links in my next presentation along with the others noted previously.

    CSS Optimiser is very cool, not sure how I’ve never seen that before… definitely an easier way than manually cleaning up your stylesheets (though there are some cases when you may not want to combine rules, e.g. for ease of maintenance or customization, etc.).

  27. […] Dan Rubin’s post about the idea, then wrote the script to implement it. What the script does is reduce all […]

  28. Chad Avatar
    Chad

    Hi, great tip! just a question, how this is different from the “Format CSS Compressed” option?

    Thanks!

  29. Dan Rubin Avatar

    @Chad: Textmate (and others) offer a way to compress stylesheets into a single line file, which is different from single-line CSS as a style (compressed equals your entire stylesheet on one line, rather than this formatting option which puts each rule on its own line).

    I’ve added an image to the article that shows the difference, which should help avoid confusion :)

  30. Chad Avatar
    Chad

    Hi Dan, thanks for the explanation. I’ve tried to compare both and still don’t see the difference that you’ve mentioned. Here are the screenshots:

    Original:
    http://i34.tinypic.com/2vl5suc.png

    Using ‘Format CSS Compressed’:
    http://i36.tinypic.com/118g35u.png

    Using ‘Format CSS Single-line’:
    http://i38.tinypic.com/33yhpa8.png

    The ‘Format CSS Compressed’ is not one line for the entire stylesheet as you can see. I really like your method, it would be much better if it can add an extra whitespace after each ‘;’ and get rid of the extra line between each rule. Or maybe I’m doing something wrong.

  31. Dan Rubin Avatar

    @Chad: Thanks for keeping me honest and accurate—somehow I must have been a bit confused when writing and even proofing the original article, since I swear that Textmate’s “Format CSS Compressed” bundle put everything on a single line in the file. *sigh*

    I’ve updated the text to reflect the differences between my macro and the default bundle—the chief reason I rolled my own was to add whitespace that makes it easier to scan the stylesheet quickly. The extra blank lines are only included if there are two or more blank lines in your original (when I group styles, I put two carriage returns between blocks of related styles).

    Of course, you can create your own version of the macro by altering the regular expressions used, and I highly recommend tweaking it to suit your own style and needs.

  32. magnao Avatar

    @Dan: Glad you think so! I’m not sure about dedicating a domain to the thing, but I did put up a Prism bundle so you can access it faster while developing. Check it out at http://magnao.com/software/flat-css/

  33. NatalieMac Avatar

    I know of a couple online tools that I’ve briefly played with:

    http://www.cleancss.com/

    http://www.codebeautifier.com/

    Both give you lots of options for organizing your code, though I have no idea why anyone would choose to alphabetize it!

  34. Antonio Wells Avatar

    My two cents… I’m a multiline idented CSS coder, for me it’s easier to find stuff in hierarchal code. I’m on two different platforms, PHP and ASP.NET. All of my newer major web applications are in .NET, but I really dont like to use Visual Studios CSS editor… I actually use Dreamweaver’s CSS editor. I just got used to it. It’s definately a preference thing.

  35. Joel Avatar

    I just wrote an online converter to translate between the two styles. You can use it here:

    http://www.newmediacampaigns.com/page/single-line-vs-multi-line-css-a-tool-to-end-the-debate

  36. Ischa Gast Avatar

    Hi Dan,

    I just discovered this regex pattern for textmate and it’s really great. But just one thing about it.

    Is it possible to add a number of tab space before the “{” that you get something like this:
    h1,h2,h3,h4,h5,h6 { font-size:100%;font-weight:bold; }

  37. […] Regex Patterns for Single Line CSSIf you are formatting your CSS style sheets single-line, you may find Dan Rubin’s Textmate macro useful and helpful. “This macro retains a single blank line where your original contained two or more blank lines (helpful if you group your rules) and adds white space that matches my standard formatting preferences (which I find makes it easier to scan quickly).” And if you don’t use Textmate, you can use a regular expression instead; it is also provided in the post. […]

  38. Sebastian Avatar
    Sebastian

    Thx for your work. I have customized it to have a space behind every semicolon, because it’s a little bit better for reading the code.

  39. […] Regex Patterns for Single Line CSSIf you are formatting your CSS style sheets single-line, you may find Dan Rubin’s Textmate macro useful and helpful. “This macro retains a single blank line where your original contained two or more blank lines (helpful if you group your rules) and adds white space that matches my standard formatting preferences (which I find makes it easier to scan quickly).” And if you don’t use Textmate, you can use a regular expression instead; it is also provided in the post. […]

  40. Cave Avatar

    I love CSS in single line flavor, but if you are using SVN type version control then it can cause problems with it merging and confilicting based on line numbers.

    If you are working in a team on a CSS build, you are forced to work multi line to tow the line, and TBH its not a problem. Just a little less scanable to me.

  41. brent Avatar

    This is great, thanks for making it public, one thing that seems to make it fall short (for me anyway) is the formatting within the lines. Since it removes all white space you’re left with something like this:

    .entry ul { margin-left:0px;padding:0 0 0 30px;padding-left:10px; }

    where I this would be more readable and preferred by anyone (like myself) who codes in single line CSS:

    .entry ul { margin-left: 0px; padding: 0 0 0 30px; padding-left: 10px; }

    [single space after the colons and semi colons]

    would this modification be easy to make?

    brent
    @
    mimoymima.com

  42. Dan Rubin Avatar

    @Brent: That shouldn’t be difficult to adjust — since this is all just a series of grep patterns, anything you can write a pattern for can be added into the series.

    Speaking of which, if anyone makes their own customized versions, I’d love to hear about them — come back and share them here in the comments!

  43. […] Regex Patterns for Single Line CSS If you are formatting your CSS style sheets single-line, you may find Dan Rubin’s Textmate macro useful and helpful. “This macro retains a single blank line where your original contained two or more blank lines (helpful if you group your rules) and adds white space that matches my standard formatting preferences (which I find makes it easier to scan quickly).” And if you don’t use Textmate, you can use a regular expression instead; it is also provided in the post. […]

  44. […] Regex Patterns for Single Line CSS – If you are formatting your CSS style sheets single-line, you may find Dan Rubin’s Textmate macro useful and helpful. “This macro retains a single blank line where your original contained two or more blank lines (helpful if you group your rules) and adds white space that matches my standard formatting preferences (which I find makes it easier to scan quickly).” And if you don’t use Textmate, you can use a regular expression instead; it is also provided in the post. […]

  45. Chad Avatar

    I use a mix of both single line and multiline CSS, for my own projects, I indent and comment single line. My first single line in a common group of CSS would be the outtermost indent so that it just looks more organized.

    I don’t think there is actually any (read -minimal) space savings by compressing a multiline into a single line format.

  46. Trip Alexander Avatar

    Looks like I am a little late to this debate, but I thought I would I would throw my way of doing it into the mix. I code CSS mult-line, but as I am certain that no more adjustments are to be made, I convert it to single line. Maybe that’s odd, but it works for me.

    Thanks Dan for the macro. Looking forward to meeting you in a week. Heading to hear you speak in Atlanta.

  47. […] He maintains his popular blog http://superfluousbanter.org where he writes about everything from Regex Patterns for Single Line CSS to logo design. Since he is a super friendly and knowledgeable guy, I decided to make his interview […]