Specifying Tab Stop Width
Posted on
I recently scoured the internet, looking for a way to specify the width of a tab stop (\t) in CSS. It turns out that CSS doesn’t offer any sort of solution. You may be asking, “Why would you even want to do that? After all, browsers ignore whitespace in HTML.” That’s true, unless of course you’re using a pre tag or any other tag with the whitespace set to pre in CSS, like the code examples on this site.
What we’ll do is use Javascript to search the element for tab stops and wrap each one in a stylable tab element. You could do this in PHP, but using Javascript is more plug-n-play because you only have to call the function once for the entire document, not each time you want a pre block. Also, when I tried to use PHP, JUSH (which I use to highlight the syntax in my code examples) would just seem to remove my new elements. That’s not cool, man.
The Javascript
This code requires jQuery. Call this after the page has loaded.
if (navigator.appName != "Microsoft Internet Explorer") {
$("code, pre").each(function(){
$(this).html($(this).html().replace(/\t/g, "<span class='code-tab'>\t</span>"));
});
}
First, we check to see if the broser is Internet Explorer. For some reason, $(this).html() removes all carriage returns when called in IE, which will certainly mess up your formatting. If the browser is IE, we’ll just ignore it and IE users will see the standard formatting, no big deal.
You can replace code, pre with whatever elements you want to affect. The /g in the RegEx tells the function to replace all matches, not just the first one (g stands for global). We’re going to leave \t in the span so the the original tab stops will be retained when users copy & paste the text or when it’s printed.
The CSS
.code-tab { display:inline-block; width:3ex; }
If the browser doesn’t support inline-block, then the tabs should show up as inline elements, which will look the same as if we did nothing. Again, that’s no problem at all.