How to Add Line Break Before an Element with CSS
In this tutorial, we’ll show some ways of adding a line break before an element. 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
<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 <p> elements 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>
Result
Books
Quizzes
Snippets
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 the “block-level” value because block elements start on a new line filling the whole available width. Here, we use <span> elements.
Example of adding a line break before <span> elements with the :before pseudo-element:
<!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>
Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in aying out print, graphic or web designs.
</p>
</body>
</html>