首頁 > web前端 > css教學 > 如何使用 CSS 為偽元素內容添加換行符?

如何使用 CSS 為偽元素內容添加換行符?

DDD
發布: 2024-11-15 08:05:02
原創
238 人瀏覽過

How to Add Line Breaks to Pseudo-Element Content Using CSS?

Adding Line Breaks to Pseudo-Element Content Using CSS

Introduction

When adding text via ::after or ::before pseudo-elements in CSS without access to HTML or PHP, the need arises to include line breaks for multi-line content. This article addresses how to achieve this using CSS.

Adding Line Breaks

To add line breaks in the content property, use the "\A" escape sequence. However, the inserted line break is subject to the "white-space" property.

Example

To illustrate, consider the following code:

#headerAgentInfoDetailsPhone:after {
  content:"Office: XXXXX \A Mobile: YYYYY ";
  white-space: pre; /* or pre-wrap */
}
登入後複製

This will add a line break after "XXXXX" and display the content as:

Office: XXXXX
Mobile: YYYYY
登入後複製

Alternative Escape Sequence

If you encounter unpredictable results when using \A, it's advisable to use \00000a instead. This ensures that arbitrary strings are correctly escaped.

Example Escape Function

For convenience, you can use the following JavaScript function to escape arbitrary text and add it to a CSS style block:

function addTextToStyle(id, text) {
  return `#${id}::after { content: "${text.replace(/"/g, '\\"').replace(/\n/g, '\\00000a')} }"`;
}
登入後複製

以上是如何使用 CSS 為偽元素內容添加換行符?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板