demosthenes.info

I’m Dudley Storey, the author of Pro CSS3 Animation. This is my blog, where I talk about web design and development with , and . To receive more information, including news, updates, and tips, you should follow me on Twitter or add me on Google+.

web developer guide

my books

Book cover of Pro CSS3 AnimationPro CSS3 Animation, Apress, 2013

my projects

CSSslidy: an auto-generated #RWD image slider. 1.5K of JS, no JQuery. Drop in images, add a line of CSS. Done.

tipster.ioAutomatically provides local tipping customs and percentages for services anywhere.

Preserving Whitespace With CSS tab-size

css / typography

Estimated reading time: 1 minute, 30 seconds

By default, HTML pages ignore anything more than a single space, and collapse them. But there are occasions for which you’ll want to preserve this space, via one of several possible techniques. The most common approach is to ignore spaces entirely, and specify margin or padding to the left or right of an element. This will remain the best solution in most cases. But there are reasons for wishing to preserve spaces that you’ve entered via the space bar or the tab key: showing the indentation before lines of code, for example, as I do in code samples in articles here.

CSS3 has direct support for this, in the form of tab-space. For presented code:

<code>ol.generic-class {</code>
<code>      property: value;</code>
<code>}</code>

We can preserve the tab before the “property: value" line with tab-space, currently supported in Firefox and Opera. We’ll enable this, and back it up in non-compliant browsers, by also setting the white-space property to pre, while using display: block to force the lines of code one underneath the other:

code { display: block; white-space: pre; -o-tab-size: 6; -moz-tab-size: 6; tab-size: 6; }

(Indicating that we want a tab to be equivalent to six spaces).

Visually, this produces the following:

ol.generic-class {
	property: value;
}

You could also use :before or :after generated content to produce spaces. Generally I’d suggest using margin or padding instead, but this is an option:

code:before { content: "        "; whitespace: pre; }

The traditional solution to adding spaces is to insert a non-breaking space, in the form of an HTML entity character, &nbsp. This should be your last option, as it means adding to your markup, which always takes more work, and is more difficult to control:

<code>ol.generic-class {</code>
<code> &nbsp; &nbsp; property: value;</code>
<code>}</code>

(Note that we keep spaces between the &nbsp; entities, which add to the final distance).

comments powered by Disqus

This site helps millions of visitors while remaining ad-free. For less than the price of a cup of coffee, you can help pay for bandwidth and server costs while encouraging further articles.