Preserve new lines and spacing in CSS
14 August, 2019
Time to read: 1 mins
Problem
You got some text (maybe from a server) that has newlines and spacing. This what the text looks like in JavaScript:
const text =
"I have a newline here\n and some extra white space for some reason.";
Now you want to display it in HTML, so you render it in JSX:
<p>{text}</p>
And this is the result:
I have a newline here and some extra white space for some reason.
The newlines and spaces are ignored.
Solution
If you want to preserve new lines and white space, you can use the white-space CSS property with the pre-wrap
value:
p {
white-space: pre-wrap;
}
So the JSX now becomes:
<p style={{ whiteSpace: "pre-wrap" }}>{text}</p>
And this is what it looks like:
I have a newline here and some extra white space for some reason.
You can also use a preformatted text element <pre>
.
Other things to read
Popular
- Reveal animations on scroll with react-spring
- Gatsby background image example
- Extremely fast loading with Gatsby and self-hosted fonts