Best ways to implement line break without by tag in CSS

Sometimes, you want to display the following text in multiple lines on the UI page

abc def
ghk lmn
pqr tuv

will code the text in HTML using p and div tags as follows

<p>abc def ghk lmn pqr tuv</p>

<p></p>

The browser displays the line

abc def ghk lmn pqr tuv

we can use the br tag to get a line break in UI.

<p>
abc def</br>
ghk lmn</br>
pqr tuv</br>
<p>

How do a line break without <br> tag

line break without br tag

This post talks about multiple ways to get a new line in HTML and CSS.

  • using display:block

In this, declared parent element p with display:block which means block-level elements are displayed in a new line

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="main.js"></script>
  </head>

  <body class="p-4">
    <p>
      <span>abc def</span>
      <span>ghk lmn</span>
      <span>pqr tuv </span>
    </p>
  </body>
</html>
p span {
  display: block;
}

You can also use display:grid and display:flex which display the text in a new line but flex and grid are not for line break purposes, but for arranging the element’s layout format.

  • using htmlpretag or CSS white-space:pre

pre tag in HTML preserves spaces and formatted text and takes the available width of the device.

<pre>
      abc def
      ghk lmn
      pqr tuv
</pre>

The only disadvantage is the font is styled using monospace and it can be overridden using font-family. The same can be achieved with div or tag using white-space: pre-wrap;.

<div style="white-space:pre-wrap">abc def ghk lmn pqr tuv</div>

you can also use pre-line or pre for white-space styles

<div style="white-space:pre-line">abc def ghk lmn pqr tuv</div>

Difference between word-space pre-line and pre-wrap and pre

prepre-linepre-wrap
whitespace and tabs are preservedPreserve white spaceswhitespaces are not preserved and collapsed, tabs are preserved
lines are broken with \n and br taglines are broken with \n, br tagline is broken with \n
use for code formattinguse for line break \nuse for line break \n and tab \t

Conclusion

Learned multiple ways to break the line into multiple without <br> tagin HTML CSS with the following approaches

  • display block css
  • HTML pre tag
  • word-space pre, pre-line or pre-wrap

And also know the difference between pre, pre-line or pre-wrap