如何实现多边形区域内外文本异色,完整显示标题内容
实现裁剪区域内外文本颜色区分的效果
问题背景
现有如下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
相关产品推荐
相关产品推荐

