CSS tab-size

CSS tab-size is used to control the length of a tab (U+0009 character). It tells the browser the number of spaces a tab takes.

tab-size applies to elements that don't collapse tabs, like <textarea>, <pre>, and any block element with whitespace: pre or whitespace: pre-wrap (see white-space). The default for most elements is collapsing tabs to a single space.

tab-size: integer
tab-size: 4;   /* number of spaces */

Browser Support: Almost full with vendor prefixes (-o and -moz). See the caniuse tab-size support table for updated information.

Using tab-size

Use tab-size after its vendor prefixed properties for the best browser support:

pre.example {
-o-tab-size: 4; -moz-tab-size: 4; tab-size: 4
Tabs in this pre tag take up 4 spaces:
	one tab
		two tabs
			three tabs
Note that tabs are not replaced by spaces.

User Tabs in textareas

tab-size allows the displaying of tabs but it doesn't enable users to insert tab characters in textareas because browsers will try to focus the next editable element (same as text fields in a form). If there are no more form elements, the textarea will still lose focus. To prevent it from happening in Chrome and Firefox use the following jQuery

	var keyCode = e.keyCode || e.which; 
		document.execCommand("InsertHTML",false,"	");

For Internet Explorer support see How to handle <tab> in textarea?. This is also required to allow tabs in divs with contenteditable="true" (HTML5).

Enabling Tabs in divs

To enable tabs in any element, set the white-space property to pre or pre-wrap. pre will only wrap on line breaks so pre-wrap is probably preferable to avoid a horizontal scroll bar. Optionally use tab-size to change the default length of 8 spaces:

div.tab-enabled {
white-space: pre-wrap; -o-tab-size: 6; -moz-tab-size: 6; tab-size: 6;
This is a div that allows tabs: one tab two tabs three tabs

Javascript for Full Support

Plugins like jQuery.tabSize are simple polyfills for tab-size. They replace existing tab characters by the adequate number of space characters in browsers that do not support the property. Note that the white-space rule is still required if not using a <pre> or <textarea>. It's as simple as:


Optimal Tab Size?

There appear to be no formal redability studies that address this matter. I'd say the most common tab size in the web is 4 spaces, when set explicitly. It is also the default tab size of editors like Notepad++ and Sublime Text. However, the default 8, and 2 spaces are also quite common.

Useful Resources

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>