{

Best ways to implement line break without br tag in CSS


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


abc def
ghk lmn
pqr tuv

will code the text in html using p and div tag as follows

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

The browser displays the line

abc def ghk lmn pqr tuv

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

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

How do a line break without 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 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 elements layout format.

  • using html pre tag 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

pre pre-line pre-wrap
whitespace and tabs are preserved Preserve white spaces whitespaces are not preserved and collapsed, tabs are preserved
lines are broken with \n and br tag lines are broken with \n, br tag line is broken with \n
use for code formatting use for line break \n use for line break \n and tab \t

Conclusion

Learned multiple ways to break the line into multiple without <br> tagin HTML CSS with 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

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.