Tailwind CSS - 内容
Tailwind CSS:使用伪元素 Content
Section titled “Tailwind CSS:使用伪元素 Content”Tailwind 提供了控制 content 属性的工具类,最常用于 ::before 和 ::after 伪元素。这允许你直接从 HTML 中为元素添加装饰性或补充性内容。
核心 Content 工具类
Section titled “核心 Content 工具类”content 的主要工具类涉及使用 before: 和 after: 等变体结合 content 工具类。
| 类示例 | CSS 输出 |
|---|---|
| after:content-[’*‘] | .after:content-['']::after { content: ''; } |
| before:content-[attr(data-tooltip)] | .before:content-[attr(data-tooltip)]::before { content: attr(data-tooltip); } |
| content-none | .content-none { content: none; } |
实际应用与示例
Section titled “实际应用与示例”这些工具类对于小型的 UI 装饰非常强大。现代 Tailwind 使用任意值([...] 语法)来允许任何字符串内容。
示例 1:标记必填字段
Section titled “示例 1:标记必填字段”一个常见的用例是在必填表单字段的标签旁添加一个红色星号 *。
<div class="space-y-4 p-4"> <label for="name" class="block text-sm font-medium text-gray-700"> Name </label> <input type="text" id="name" class="border border-gray-300 rounded-md p-2 w-full">
<label for="email" class="block text-sm font-medium text-gray-700 after:content-['*'] after:ml-0.5 after:text-red-500"> Email (Required) </label> <input type="email" id="email" class="border border-gray-300 rounded-md p-2 w-full"></div>示例 2:自定义列表项目符号或图标
Section titled “示例 2:自定义列表项目符号或图标”你可以用自定义内容(如表情符号或 SVG 图标)替换默认的列表项目符号。
<ul class="list-none space-y-2 p-4"> <li class="before:content-['✅'] before:mr-2"> Modern project setup </li> <li class="before:content-['✅'] before:mr-2"> Clean, readable code </li> <li class="before:content-['❌'] before:mr-2 text-gray-400"> Outdated practices </li></ul>示例 3:使用数据属性作为 Content
Section titled “示例 3:使用数据属性作为 Content”对于更动态的内容,你可以从 HTML 数据属性中提取文本。这对于简单的工具提示或引用很有用。
<blockquote class="p-4 bg-gray-100 border-l-4 border-gray-400 italic before:content-[open-quote] after:content-[close-quote]" cite="Ada Lovelace"> <p class="mb-2">The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform.</p> <footer class="text-right text-sm text-gray-600 after:content-['—_attr(cite)']"></footer></blockquote>重要可访问性考量
Section titled “重要可访问性考量”警告: 通过 ::before 和 ::after 添加的内容通常不会被屏幕阅读器播报。它应被视为纯粹的装饰性内容。
- 不要使用伪元素来添加关键信息,例如错误消息或重要标签。
- 要将它们用于样式元素,如自定义项目符号、引号或旁边有文本替代方案的装饰性图标。