Home >Web Front-end >CSS Tutorial >How to Achieve Line Breaks in CSS Without HTML Tags?

How to Achieve Line Breaks in CSS Without HTML Tags?

DDD
DDDOriginal
2024-10-31 08:26:29949browse

How to Achieve Line Breaks in CSS Without HTML Tags?

CSS Line Breaks without HTML Tags

Achieving line breaks solely with CSS, without introducing additional HTML elements, can be achieved using the following method:

Problem:

In a bullet list, you wish to have a line break after an

element but not before, maintaining the

on the same line. Conventional solutions suggest setting display: block; for the

, but this breaks the inline nature of the element.

CSS Solution:

The solution lies in using CSS pseudo-elements to introduce a line break. Here's the CSS code:

h4 {
  display: inline;
}
h4:after {
  content: "\a";
  white-space: pre;
}

Explanation:

  • display: inline; keeps the

    on the same line as other text.

  • h4:after creates a pseudo-element after the

    element.

  • content: "a"; injects a line break character into the pseudo-element.
  • white-space: pre; preserves the line break.

Demo:

An example of this technique can be found here: http://jsfiddle.net/Bb2d7/

Origin:

The inspiration for this trick came from this StackOverflow answer: https://stackoverflow.com/a/66000/509752

The above is the detailed content of How to Achieve Line Breaks in CSS Without HTML Tags?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn