CSS provides flexible options to add or manage line breaks in your content. Here are some effective techniques:
1. Using the white-space Property
The white-space property allows controlling how text wraps and respects line breaks within an element.
<html>
<head>
<style>
.break {
white-space: pre-wrap;
}
</style>
</head>
<body>
<div class="break">
This is the first line.
This is the second line.
</div>
</body>
</html>
- white-space: pre-wrap; preserves line breaks in the HTML source code while wrapping long lines automatically.
- The text inside the .break class will render with line breaks exactly as written.
2. Using display: block for Inline Elements
Changing the display property of inline elements to block can create line breaks between elements.
<html>
<head>
<style>
.break {
display: block;
margin-top: 10px;
}
</style>
</head>
<body>
<span class="break">Line 1</span>
<span class="break">Line 2</span>
</body>
</html>
- Setting display: block; makes inline elements occupy their own line, creating a visual line break.
3. Using ::after Pseudo-Element
The ::after pseudo-element can insert content, including line breaks.
<html>
<head>
<style>
.break::after {
content: "\A";
white-space: pre;
}
</style>
</head>
<body>
<p class="break">This line will break here</p>
<p>Second line </p>
</body>
</html>
- content: "\A"; inserts a line break after the element's content.
- white-space: pre; ensures the line break is respected in the rendered output.
Note: CSS cannot create a true line break exactly like the <br> element. However, it can simulate line breaks in several ways:
- Using display: block to force a new line.
- Using white-space to preserve line breaks.
- Using content: "\A" in pseudo-elements to insert a break.