Open In App

How To Add Line Break in CSS?

Last Updated : 11 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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
<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
<html>
<head>
    <style>
        .break {
            display: block;
        }
    </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
<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.

Use Line Break in CSS – FAQs

Can I use both ::before and ::after together to add multiple line breaks?

Yes, combining both pseudo-elements allows you to insert multiple line breaks. For example, you can add line breaks before and after an element.

Is there any functional difference between using ::before and ::after for line breaks?

No, they work similarly for inserting line breaks, except for the position where the line break appears. ::before inserts it before the content, while ::after places it after.

Can these approaches be used in all browsers?

These methods are supported in modern browsers, including Chrome, Firefox, Safari, and Edge. For older browsers, support for \A may be limited.

How can I insert multiple line breaks with CSS?

Use multiple \A characters in the content property, like this: content: “\A\A”; to add more than one line break.

Can line breaks be removed using CSS?

Yes, you can disable the line break by overriding the content property, for example: .line-break::before { content: “”; }.



Next Article

Similar Reads

three90RightbarBannerImg
  翻译: