HTML Space Display Issues

· 2 min read · 271 Words · -Views -Comments

In actual web development, I’ve seen some people habitually use character entities to control spacing like hello world. Personally, I don’t think this is good practice. Here’s a simple explanation.

 

Because HTML is a markup language (essentially code), some characters in HTML are reserved characters - spaces, greater than, less than signs, similar to / . in regular expressions which are also reserved characters. But sometimes we want to display these characters as text. How do we do that? HTML’s solution is to use character entities, for example, space is  .

Notes

  • This is an English space
  •   stands for non-breaking space
  • Entity names are case-sensitive!

Equivalent Writing

For example, in React projects, because JSX is still essentially JavaScript, we can use variables to represent spaces, like hello{' '}world, which is actually equivalent to hello world.

10 Spaces?

Observant readers will notice that with text spaces, hello{' '}world still results in only 1 space. Why? Because browsers always truncate the number of spaces in HTML pages. If you want to display 10 spaces, you need to use 10 character entities  .

Disadvantages

Whether using {’ ‘} or  , the drawback is that the displayed width of this space varies with different fonts. Another disadvantage is that if you need 10, 20 spaces, it’s much less precise and flexible than using CSS control.

What Should Be Done

In my opinion:

  • If it’s just a simple space and the font variation is acceptable, use text space {’ ‘} because it’s simple enough and part of the code anyway
  • If you need many spaces, please consider using CSS solutions instead.

Reference Documentation

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover