Wrangling white-space

When creating the template for the category links on this blog, I ran into a tiny problem of getting the text output, HTML-elements and white-space in the source to play nicely.

Basically the problem was that I wanted a nice, readable sentence for spelling out which category or categories that the post was associated with.

I wanted this:

<p>Filed under <a href="/blog/category/web-development/">Web Development</a>, <a href="/blog/category/personal-stuff/">Personal stuff</a> and <a href="/blog/category/meta-stuff">Meta stuff</a>.</p>

Because of how the template tags in Perch are treated, there’s quite a bit of whitespace added. Since it’s between words, it normally just collapses to a single whitespace when interpreted as text, which is fine. The problem is the comma, directly after the first category link in the sentence. Since there is a conditional there in the template code, line-breaks are introduced and subsequently interpreted as white-space between word and comma:

<p>Filed under 
<a href="/blog/category/web-development/">Web Development</a>
, 
<a href="/blog/category/personal-stuff/">Personal stuff</a>
 and 
<a href="/blog/category/meta-stuff">Meta stuff</a>
.</p>

This results in the output Filed under Web Development , Personal stuff and Meta stuff—note the extra ugly space after the comma.

This is the same problem as with creating horizontal lists with display: inline-block; by the way: there will be gaps inbetween the list-items unless they are output on the same line with no spaces inbetween. Twitter Bootstrap has the same issue with grouping buttons together into one ”split-control”: they ”solve it” by putting font-size: 0; on the enclosing element (thus eliminating effects of white-space), and then re-setting the font-size in pixels on the individual buttons in the group. The problem is that this will srew with setting font-sizes in em:s instead of px, since the font-size of 0 will be inherited.

I the end, I resorted to using a span-element around the comma, and set a negative left margin on it that was roughly equal to the white-space: I’m sure the issue could have been resolved in a number of different ways, but the interesting thing whilst digging about various white-space handling rules was that I found the text-space-collapse property, currently being defined in CSS Text Level 4. It discusses several potential values for this property, including collapse, preserve, preserve-breaks and discard (among others).

As far as I can tell, there’s no implementations yet (and the discussion around it seems fairly complex, with intenationalization issues being one difficulty), but the gist of it is that it allows you to control how white-space collapses inside/between elements in a more detailed way. Would be nice to have.