Explain Codes LogoExplain Codes Logo

How to insert spaces/tabs in text using HTML/CSS

html
html-entities
css-whitespace
custom-spacing
Anton ShumikhinbyAnton Shumikhin·Jan 20, 2025
TLDR

Emulate single spaces with repeated  , tabs with   or 	. Use CSS property white-space: pre; to preserve your hard-earned manual spacing.

Example:

Space:  Double space Tab: Em space tab
.pre-tab { white-space: pre; /* Tell CSS to 'preserve' my sanity */ }
<div class="pre-tab">Manual tab</div>

These codes go right into your HTML, right where you need that 'space'.

HTML Entities: When you need 'space'

HTML Entities like &nbsp;, &ensp;, and &emsp; grant you total control over space within your content. Pop a &nbps; for a non-breaking space. And if you reaaaally need that tab effect, use &emsp; or lead with &ensp; for half the distance.

Key points:

  • &nbsp; says, 'One space, coming right up!'
  • &emsp; is the big kahuna, it's your tab equivalent.
  • &ensp; pulls up half-way, just like a good dinner guest.

Whitespace Management 101: Meet CSS

Your CSS property white-space: defines whitespace rules. Your options run from eliminating white spacing (normal) to honoring every sacred space (pre), line breaks included.

.white-space-pre { white-space: pre; /* Every. Single. Space. */ }

Note that CSS white-space: pre; can help keep the original formatting of text, handling both spaces and tabs.

Custom spacing: We can do that!

HTML's entities not hitting the mark? Pull out the span kung fu. Inline span elements with a defined width for horizontal space, or block span elements with defined height for vertical.

Text before<span style="display: inline-block; width: 30px;"></span>Text after

That'll give you custom 30px of space right between "Text before" and "Text after". Tweak the width to fit the spacing you need.

Tread carefully: The Pitfalls

Don't use the less than < and greater than > characters to create tabs. Reserved for HTML tags, they can accidentally create unexpected rendering issues or expose your code to security vulnerabilities.

More spac-ing? Check out the HTML Entities list

HTML provides tricky entities like  ,  , and ​. Opens up a whole universe of fine typography.

Coding best practices, because we care

Code with the future in mind. Here are some best practices for an efficient plan:

  • Use CSS classes to apply styles 💪, including whitespace, across elements.
  • Mind the readability, don't drown in white space.
  • Keep accessibility in mind; screen readers may arrive at unexpected pronunciation with excess &nbsp;.
  • Code consistently. Follow the project's or team's standards when it comes to spacing and indentation.