In HTML, there are two types of whitespaces: regular spaces and non-breaking spaces, denoted by
.
A non-breaking space is a space that will not break into a new line. When two words are separated by a non-breaking space, they will remain together on the same line.
Let's consider an example using regular spaces in HTML.
If we try to resize the output window for the above example, we can see that the words Tom, and, and Jerry get split into different lines.
Let's update the example to use
instead of regular spaces.
If we resize the output window now, we can see that the words Tom, and, and Jerry stay on a single line.
Using
is particularly useful when you want to display text in a single line, such as 10:00 PM
, 5 km/h
, and so on.
Another important distinction between regular spaces and
is that regular spaces are truncated by browsers. If you include 10 spaces in your text, the browser will remove 9 of them. To ensure that you retain all the spaces you need, you should use the
character entity:
However, it is not advisable to add spaces using a long chain of
like this. Instead you can use CSS styles such as margin
, padding
etc.
The above approaches in HTML can be applied to add spaces in JSX as well. Alternatively, you can add space in JSX using the syntax {" "}
:
The JSX syntax {" "}
for adding space behaves similarly to regular spaces in HTML. We prefer to use {" "}
, as it makes the space explicit and intentional.