Home >Web Front-end >CSS Tutorial >How to Display Multiline Data Attribute Content with New Lines using CSS?

How to Display Multiline Data Attribute Content with New Lines using CSS?

DDD
DDDOriginal
2024-11-18 05:46:02548browse

How to Display Multiline Data Attribute Content with New Lines using CSS?

Manipulating Data Attributes and Pseudo-Element Content with New Lines

In CSS, it's possible to retrieve values from data attributes using the attr() function and display them as content using pseudo-elements. However, incorporating new lines within these data attributes can be challenging.

Issue: New Line Character in Data Attribute

Consider the following code example:

[data-foo]:after {
    content: attr(data-foo);
    background-color: black;
}
<div data-foo="First line \a Second Line">foo</div>

Despite using the "a" escape sequence, which represents a new line character in CSS, the content within the data-foo attribute remains on a single line.

Solution: Enhanced Data Attribute Syntax and White-Space Configuration

To enable multiline data attributes, modify the syntax as follows:

[data-foo]:after {
    content: attr(data-foo);
    background-color: black;
    color: white;
    white-space: pre;
    display: inline-block;
}
<div data-foo='First line &amp;#xa; Second Line'>foo</div>

In this modified version:

  • white-space: pre;: Preserves the whitespace characters within the data attribute, including new lines.
  • display: inline-block;: Prevents text wrapping and allows the content to flow on multiple lines.
  • : HTML entity for a line break.

The above is the detailed content of How to Display Multiline Data Attribute Content with New Lines using CSS?. 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