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

如何实现多边形区域内外文本异色,完整显示标题内容

实现裁剪区域内外文本颜色区分的效果

问题背景

现有如下CSS与HTML代码:

<style>
  .heading-container {
    clip-path: polygon(0% 24.75%, 49.5% 49.88%, 99% 75%, 0% 75%);
    background: #000;
    padding: 20px;
  }

  h1 {
    color: white;
  }
</style>
<div style="background-color:pink">
  <div class="heading-container">
    <h1>Lorem Ipsum Heading Test Lorem Ipsum Heading Test</h1>
  </div>
</div>

当前效果中部分文本被clip-path裁剪,需要实现完整显示句子——被裁剪的原白色文本在粉色背景上显示为黑色,即裁剪区域内文本为白色(搭配黑色背景),裁剪区域外文本为黑色(搭配粉色背景)。

解决方案思路

通过两层文本叠加实现需求:

  • 底层放置完整的黑色文本,确保所有内容都能显示
  • 上层放置带clip-path的黑色背景容器,内部是白色文本,通过绝对定位完全覆盖在底层文本上
  • 上层容器的clip-path会裁剪掉部分白色文本和黑色背景,露出底层的黑色文本,从而实现裁剪区域内外文本颜色不同的效果

修改后的完整代码

<style>
  .pink-bg {
    background-color: pink;
    position: relative; /* 作为上层容器的定位参照 */
    padding: 20px; /* 保留内边距,避免文本溢出容器 */
  }

  .heading-container {
    clip-path: polygon(0% 24.75%, 49.5% 49.88%, 99% 75%, 0% 75%);
    background: #000;
    padding: 20px;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box; /* 确保内边距不影响容器尺寸 */
  }

  .bottom-text {
    color: black;
    margin: 0; /* 清除默认margin,避免位置偏移 */
  }

  .top-text {
    color: white;
    margin: 0; /* 清除默认margin,确保和底层文本对齐 */
  }
</style>
<div class="pink-bg">
  <!-- 底层黑色文本 -->
  <h1 class="bottom-text">Lorem Ipsum Heading Test Lorem Ipsum Heading Test</h1>
  <!-- 上层带裁剪的白色文本容器 -->
  <div class="heading-container">
    <h1 class="top-text">Lorem Ipsum Heading Test Lorem Ipsum Heading Test</h1>
  </div>
</div>

关键细节说明

  • 给粉色背景容器设置position: relative,让上层的.heading-container可以基于它做绝对定位
  • 两层h1都清除默认margin,保证文本位置完全重合
  • 上层容器设置box-sizing: border-box,避免padding导致容器尺寸超出粉色背景容器
  • 上层容器的width: 100%和height: 100%确保完全覆盖底层文本区域

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:23:29