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

纯CSS实现矩形中部镂空圆形:消除特定位置box-shadow求助

仅用CSS实现带上下半圆连接的卡片样式问题

我希望仅用CSS实现带上下半圆连接的卡片样式(目标样式:目标效果),目前已实现的效果为当前效果。遇到的问题是无法去除伪元素特定位置的box-shadow,尝试过用clip-path裁剪圆形,但阴影仍然存在。

现有代码

CSS代码

.box {
    width: 50%;
    min-height: 100px;
    box-shadow:  0 0 0.125rem 0 hsla(0, 0%, 0%, 0.4);
    position: relative;
    border-radius: 10px;
    z-index: 0;
    padding: 12px;
    margin-bottom: 4px;
}


.box::before {
    content: '';
    position: absolute;
    width: 20px;
    height: 10px;
    border-radius: 50%;
    box-shadow:  0 0 0.125rem 0 hsla(0, 0%, 0%, 0.4);
    transform: translateX(-50%);
    background-color: white;
    border-bottom-left-radius: 110px;
    border-bottom-right-radius: 110px;
    border-top: 0;
    clip-path: inset(0px -10px -10px -10px);
}

.box::after {
    content: '';
    position: absolute;
    width: 20px;
    height: 10px;
    box-shadow:  0 0 0.125rem 0 hsla(0, 0%, 0%, 0.4);
    transform: translateX(-50%);
    background-color: white;
    border-top-left-radius: 110px;
    border-top-right-radius: 110px;
    border-bottom: 0;
    clip-path: inset(0px -10px -10px -10px);
}

.box::before {
    top: -1.1px;
    left: 50%;
}

.box::after {
    bottom: -1px;
    left: 50%;
}

HTML代码

<div class="box">
  Content
</div>

解决方案

问题核心是box-shadow作用于元素的整个外部轮廓,clip-path仅能裁剪元素本身,无法裁剪外部阴影。可以通过以下方式修复:

  1. 移除伪元素的全向box-shadow,改为仅添加左右方向的阴影,避免上下出现多余阴影。
  2. 简化伪元素的圆角设置,调整位置确保和父元素无缝衔接,用白色背景覆盖父元素对应位置的阴影。

修改后的CSS代码:

.box {
    width: 50%;
    min-height: 100px;
    box-shadow: 0 0 0.125rem 0 hsla(0, 0%, 0%, 0.4);
    position: relative;
    border-radius: 10px;
    z-index: 0;
    padding: 12px;
    margin-bottom: 4px;
    background-color: white; /* 确保父元素背景为白色,避免透底 */
}

.box::before {
    content: '';
    position: absolute;
    width: 20px;
    height: 10px;
    transform: translateX(-50%);
    background-color: white;
    /* 仅保留左右阴影,上下无阴影 */
    box-shadow: -2px 0 0.125rem -1px hsla(0, 0%, 0%, 0.4), 
                2px 0 0.125rem -1px hsla(0, 0%, 0%, 0.4);
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    top: -9px; /* 调整位置,让半圆顶部与父元素顶部无缝衔接 */
    left: 50%;
}

.box::after {
    content: '';
    position: absolute;
    width: 20px;
    height: 10px;
    transform: translateX(-50%);
    background-color: white;
    /* 仅保留左右阴影,上下无阴影 */
    box-shadow: -2px 0 0.125rem -1px hsla(0, 0%, 0%, 0.4), 
                2px 0 0.125rem -1px hsla(0, 0%, 0%, 0.4);
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    bottom: -9px; /* 调整位置,让半圆底部与父元素底部无缝衔接 */
    left: 50%;
}

说明

  • 伪元素直接使用对应方向的半圆圆角,简化形状逻辑。
  • 通过控制阴影的偏移量和模糊半径,仅保留左右两侧的阴影效果,彻底消除上下多余阴影。
  • 调整伪元素的top/bottom值,确保与父元素无缝衔接,同时用白色背景覆盖父元素在该位置的阴影,保证视觉连贯性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 11:07:02