How to Add a Line Break Before an Element with CSS

In this tutorial, we’re going to show some ways of adding a line break before an element. Actually, this can easily be done with a few steps.

We need to use the CSS white-space property to specify how the space inside an element must be handled. Particularly, we’ll use the “pre” value of this property.

Start with creating HTML.

Create HTML

  • Use an <h1> element and three <p> elements.
<h1>W3Docs</h1>
<p>Books</p>
<p>Quizzes</p>
<p>Snippets</p>

Add CSS

  • Use the ::before pseudo-element.
  • Add a carriage return character (\A) in the content.
  • Set the white-space property to “pre”.
p::before {
  content: "\A";
  white-space: pre;
}

Here, you can see the full code.

Example of adding a line break before an element with the :before pseudo-element:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p::before { 
      content: "\A"; 
      white-space: pre; 
      } 
    </style>
  </head>
  <body>
    <h1>W3Docs</h1>
    <p>Books</p>
    <p>Quizzes</p>
    <p>Snippets</p>
  </body>
</html>

In the next example, a line break before an element is also added with the :before pseudo-element and by using the carriage return character and the display property set to “block-level” since a block-level element will start on a new line and take up the whole available width. Here, we use <span> elements.

Example of adding a line break before an element using the display property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      span::before { 
      content: "\A";  
      white-space: pre;      
      display: block;  
      } 
    </style>
  </head>
  <body>
    <h1>W3Docs</h1>
    <span>Books</span>
    <span>Quizzes</span>
    <span>Snippets</span>
  </body>
</html>

In our last example, a line break is added without the use of the :before pseudo-element. We only set the white-space property to the “pre-line” value for the <p> element.

Example of adding a line break before an element without the :before pseudo-element:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {  
      color:#fc0303; 
      white-space: pre-line; 
      font-size: 20px;
      } 
    </style>
  </head>
  <body>
    <h1>W3Docs</h1>
    <p> 
      Books
      Quizzes
      Snippets
    </p>
  </body>
</html>

Do you find this helpful?

Related articles