You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用HTML和CSS实现文本高亮效果?已尝试mix-blend-mode遇问题

问题描述

我希望用HTML和CSS实现斜向文本高亮效果,此前尝试使用mix-blend-mode属性,但出现了背景也被反转的问题。以下是我的实现代码:

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Masked Text Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="masked-text">
        Customized solutions support product company success throughout company life cycle.
    </div>
</body>
</html>

CSS代码

.masked-text {
  width: 300px;
  overflow: hidden;
  
  position: relative
}

.masked-text::after {
  content: '';
  width: 20px;
  
  transform: rotate(15deg);
  background-color: orange;
  mix-blend-mode: difference;
  
  position: absolute;
  top: -10%;
  bottom: -10%;
  
}
解决方案

要解决背景被mix-blend-mode反转的问题,关键是让混合效果仅作用于文本,而非整个页面背景。以下两种方法可以实现:

方法1:隔离混合上下文

给父容器添加isolation: isolate,限制混合模式的作用范围,同时调整伪元素的层级和位置,确保只与文本交互:

.masked-text {
  width: 300px;
  overflow: hidden;
  position: relative;
  isolation: isolate; /* 隔离上下文,避免影响外部背景 */
  color: #000; /* 明确文本颜色,保证混合效果稳定 */
}

.masked-text::after {
  content: '';
  width: 20px;
  transform: rotate(15deg);
  background-color: orange;
  mix-blend-mode: difference;
  position: absolute;
  top: -10%;
  bottom: -10%;
  left: 60px; /* 调整到需要高亮的文本位置 */
  z-index: 1; /* 确保高亮层在文本上方 */
}

方法2:直接实现文本高亮(无混合模式副作用)

如果不需要依赖混合模式,使用background-clip: text可以更精准地实现斜向文本高亮,且不会影响背景:

修改后的HTML

<div class="highlighted-text">
  Customized solutions support product company success throughout company life cycle.
</div>

对应CSS

.highlighted-text {
  width: 300px;
  color: transparent;
  /* 斜向橙色高亮条+黑色文本底色 */
  background: linear-gradient(15deg, orange 22px, transparent 22px), #000;
  background-clip: text;
  -webkit-background-clip: text; /* 兼容webkit内核浏览器 */
}

两种方法对比:方法1保留了混合模式的颜色反转效果,适合需要特殊色彩交互的场景;方法2更直接,无混合模式兼容性问题,适合纯粹的高亮需求。

内容的提问来源于stack exchange,提问作者huanz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 01:30:58