Explain Codes LogoExplain Codes Logo

How to get a tab character?

html
responsive-design
best-practices
web-development
Alex KataevbyAlex Kataev·Oct 25, 2024
TLDR

In HTML, tab character is represented by &#9;. Use the <pre> element to preserve this tab character:

<pre>Text&#9;Tabs in action</pre>

Alternatively, use the CSS property white-space: pre; to an element, which works like the <pre> element:

<div style="white-space: pre;">Text&#9;More tab action</div>

Understanding Tab Characters in HTML

Tabs in HTML are treated as whitespace characters. They get collapsed into a single space when rendered in a browser, except when used within a <pre> tag. Here's a bit of trivia: a literal tab corresponds to Unicode character U+0009.

Try embedding a literal tab in a text editor or IDE. If it's contained within <pre>, the tab character will render properly. If not, size might vary, and extra line breaks may occur. Have fun experimenting!

Advanced use of tabs using CSS

For creating space among text equal to a tab character, you can use CSS to style a <span> element:

<span style="display: inline-block; width: 40px;"></span> <!-- Sometimes, space _does_ matter -->

You can vary the width to change the space created by this tab. For more control and cleaner code, use margin or padding with div elements:

<div style="margin-left: 40px;">Indented content here</div> <!-- Clean, neat, and organized text! -->

The Art of Whitespace in HTML

Understanding how HTML handles whitespace is key for proper layout design. In addition to <pre>, you can use HTML entities &emsp; and &ensp; for wider spaces that mimic tabs. These represent em and en spaces respectively.

In monospace fonts:

  • &ensp; is treated as a single space
  • &emsp; usually represents a double space

Try to avoid non-breaking spaces (&nbsp;), as they might muddle up your HTML.

Replicating Tab Effects

When a tab character isn't practical, use the following trick to mimic its effects:

<span style="display: inline-block; width: 2ch;"> </span> <!-- Give me some space, please! -->

This creates an inline-block span with the width of two characters (2ch). Adjust as needed for variable fixed-width tabular spacing.

Exploring Tab Usage

Tabs can be used creatively:

  • Redefined website navigation
  • Linear and readable forms
  • Clean and indented <code> blocks
  • Enhanced webpage accessibility using the tabindex

Understanding these applications enhances your HTML tab expertise.

When not to use tabs

Tabs aren't the best choice in all situations, such as:

  • Screen Readers: Tabs are often ignored, impairing accessibility.
  • Responsive Design: Tabs can ruin layout on smaller screens.
  • Email Content: Most email clients strip tab characters.

It's best to stick to responsive CSS techniques in such cases.