Line break in HTML with '\n'
Are you wondering why n doesn’t create a visible line break in your HTML output like it does in code or text files? Let’s explore how line breaks actually work in HTML and what the correct way is to display them in a browser.
If you're using
in HTML and expecting it to create a line break on the webpage, you might be surprised — it doesn’t actually do what you think. While
(newline) works in programming languages and plain text files, HTML doesn't treat it as a visual line break in the rendered page.
Why doesn't
work in HTML?
HTML ignores whitespace like newlines and tabs when rendering content. So even if your HTML source has
, it won't affect the way text appears in the browser.
- How to add line breaks in HTML:
- Here are the proper ways to create visible line breaks:
Use the
tag
Example:
HelloWorld
This will display as:
Hello
World
Use CSS with white-space: pre-line or pre
If your content includes
(like from user input), you can use CSS to make the browser respect it:
This is line one.
This is line two.
Use the
tag
This tag preserves all whitespace and line breaks:
Line one
Line two
Tip:
- If you're dynamically inserting content via JavaScript or from a backend and it includes
, just replace it with
for visual breaks.
- So, while
is great for code, in HTML you’ll need to use the proper tools to make those line breaks show up!