前端

CSS - 伪元素的妙用

什么是CSS伪元素?

CSS伪元素允许我们在文档中插入虚拟的HTML元素,而无需在实际的HTML标记中添加它们。 目前最常用的伪元素有:

  • ::before
  • ::after
  • ::first-line
  • ::first-letter

记录几种巧妙的用法:

1. 阴影渐变文字

使用 ::before 伪元素可以轻松地为元素添加图标:

.shadow-text { color: white; font-size: 100px; font-weight: bold; position: relative; } .shadow-text::after { content: "Hello World"; color: gray; font-size: 100px; font-weight: bold; position: absolute; left: 0; transform: skewX(45deg) scaleY(0.6) translate(-40px, 25px); z-index: -1; filter: blur(2px); mask: linear-gradient(transparent, #aaaaaa); }
<div> <span class="shadow-text">Hello World</span> </div>

2. 创建工具提示

.tooltip { position: relative; } .tooltip::after { content: attr(data-tooltip); position: absolute; bottom: 100%; left: 50%; transform: translateX(-50%); background-color: #333; color: #fff; padding: 5px; border-radius: 3px; opacity: 0; transition: opacity 0.3s; } .tooltip:hover::after { opacity: 1; }

3. 清除浮动

使用 ::after 伪元素可以轻松清除浮动:

.clearfix::after { content: ""; display: block; clear: both; /* 目前推荐使用 */ display: flow-root; }

4. 创建引用样式

使用 ::before::after 可以为引用添加漂亮的样式:

blockquote { position: relative; padding: 20px; background: #f9f9f9; } blockquote::before, blockquote::after { content: '"'; font-size: 50px; position: absolute; color: #ccc; } blockquote::before { top: 0; left: 10px; } blockquote::after { bottom: -20px; right: 10px; }
<blockquote>Hello World</blockquote>

5. 创建计数器

使用 ::before 结合CSS计数器可以自动为元素编号:

.container { counter-reset: section; } .container h2::before { counter-increment: section; content: "编号 "counter(section) ": "; }
<div class="container"> <h2>Hello World1</h2> <h2>Hello World2</h2> <h2>Hello World3</h2> </div>
Previous
脚本和模块