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
Release: 2024-11-18 05:46:02
Original
561 people have browsed it

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;
}
Copy after login
<div data-foo="First line \a Second Line">foo</div>
Copy after login

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;
}
Copy after login
<div data-foo='First line &amp;#xa; Second Line'>foo</div>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template