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

如何使用CSS在卡片顶部实现反向圆角(凹口)效果?

实现顶部带自适应反向圆角凹口的红色卡片

方案一:纯色背景下的简易实现(无JS)

适合页面背景为纯色的场景,通过伪元素模拟反向圆角,凹口宽度随文本自动适配:

HTML结构

<div class="card">
  <div class="notch">
    <span class="notch-text">自适应凹口文本</span>
  </div>
  <div class="card-content">
    这里是卡片内部的文本内容,可自由添加多行文字,不会被凹口遮挡。
  </div>
</div>

CSS代码

.card {
  position: relative;
  width: 300px;
  background-color: #e53e3e;
  border-radius: 8px;
  overflow: hidden; /* 彻底解决元素溢出容器问题 */
  padding: 30px 16px 16px; /* 顶部留空给凹口 */
}

.notch {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: flex-end;
}

.notch-text {
  background-color: #e53e3e;
  padding: 0 12px;
  line-height: 24px;
  color: #fff;
  z-index: 2;
}

/* 左右反向圆角弧形(颜色和页面背景一致) */
.notch::before,
.notch::after {
  content: '';
  width: 16px;
  height: 16px;
  background-color: #fff; /* 替换为你的页面背景色 */
  border-bottom-right-radius: 16px;
  position: relative;
  bottom: -8px;
}

.notch::after {
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 16px;
}

方案二:透明背景/复杂背景下的通用实现(需JS)

如果页面背景不是纯色,用clip-path切割卡片顶部,配合JS动态计算文本宽度,实现完全透明的凹口:

HTML结构

<div class="card">
  <div class="notch">
    <span class="notch-text">自适应凹口文本</span>
  </div>
  <div class="card-content">
    这里是卡片内部的文本内容,可自由添加多行文字,不会被凹口遮挡。
  </div>
</div>

CSS代码

.card {
  position: relative;
  width: 300px;
  background-color: #e53e3e;
  border-radius: 8px;
  overflow: hidden;
  padding: 30px 16px 16px;
  /* JS动态设置凹口半宽变量 */
  --notch-half-width: 0px;
}

.notch {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
}

.notch-text {
  display: inline-block;
  padding: 0 12px;
  line-height: 24px;
  color: #fff;
  z-index: 1;
}

/* 用clip-path切割出带反向圆角的凹口 */
.card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 16px;
  background-color: #e53e3e;
  clip-path: polygon(
    0 0,
    calc(50% - var(--notch-half-width) - 16px) 0,
    calc(50% - var(--notch-half-width)) 100%,
    calc(50% + var(--notch-half-width)) 100%,
    calc(50% + var(--notch-half-width) + 16px) 0,
    100% 0,
    100% 100%,
    0 100%
  );
}

JS代码(动态计算文本宽度)

const notchText = document.querySelector('.notch-text');
const halfWidth = notchText.offsetWidth / 2;
document.querySelector('.card').style.setProperty('--notch-half-width', `${halfWidth}px`);

// 如果文本内容动态变化,可监听元素变化重新计算
new ResizeObserver(() => {
  const newHalfWidth = notchText.offsetWidth / 2;
  document.querySelector('.card').style.setProperty('--notch-half-width', `${newHalfWidth}px`);
}).observe(notchText);

关键解决点

  • 用overflow: hidden彻底解决元素溢出容器的问题
  • 方案一通过伪元素+背景色模拟反向圆角,无需JS,适配纯色背景
  • 方案二用clip-path切割卡片,配合动态CSS变量实现完全透明的自适应凹口,适配所有背景场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:55:03