css 如何实现这样的文字填充背景效果?

css 如何实现这样的文字填充背景效果?

image.png

阅读 744
avatarAI BotBETA

在CSS中实现文字填充背景效果(文字内部显示背景图片/渐变,外部透明)可以通过background-clip: text配合透明文字颜色来实现。以下是具体方法:

核心代码实现

.text-bg {
  /* 设置文字的背景(图片/渐变/颜色) */
  background: linear-gradient(to right, #ff8a00, #da1b60); /* 示例渐变 */
  background-size: cover;

  /* 关键属性:将背景裁剪到文字区域 */
  -webkit-background-clip: text; /* Safari/Chrome 支持 */
  background-clip: text;

  /* 使文字颜色透明,显示底层背景 */
  color: transparent;
  
  /* 可选样式 */
  font-size: 5rem;
  font-weight: bold;
  display: inline-block;
}

HTML示例

<span class="text-bg">背景文字效果</span>

关键属性说明

  1. background-clip: text

    • 将背景裁剪限制在文字形状内部
    • 需配合-webkit-前缀保证浏览器兼容性
  2. color: transparent

    • 使文字本身透明,露出底层背景
  3. 背景设置

    • 可替换为:

      • 图片:background: url(image.jpg)
      • 纯色:background: #3498db
      • 渐变:background: linear-gradient(...)

浏览器兼容性

浏览器支持版本
Chrome58+ (带-webkit-)
Safari14+ (带-webkit-)
Firefox49+
Edge79+

高级技巧

  1. 添加动画效果

    .text-bg {
      background-size: 200% auto;
      animation: shimmer 3s linear infinite;
    }
    
    @keyframes shimmer {
      to { background-position: 200% center; }
    }
  2. 文字描边增强效果

    .text-bg {
      text-shadow: 
     2px 2px 4px rgba(0,0,0,0.3), /* 外阴影 */
     -1px -1px 0 white, 1px -1px 0 white, /* 白色描边 */
     -1px 1px 0 white, 1px 1px 0 white;
    }
  3. 支持旧版浏览器的备选方案

    @supports not (background-clip: text) {
      .text-bg {
     position: relative;
     color: #000; /* 后备文字颜色 */
      }
      .text-bg::before {
     content: attr(data-text);
     position: absolute;
     background: linear-gradient(...);
     -webkit-background-clip: text;
     background-clip: text;
     color: transparent;
      }
    }
💡 提示:设计时建议使用深色背景或添加文字阴影,确保在复杂背景下保持可读性。
1 个回答

inline 的元素设置 line-heightbackgroud-color 就是这样的效果。

图片.png
Vue SFC Playground

如果要继续优化,可以考虑设置 text-align 相关的样式。