CSS实现透明内层+渐变边框的优雅方案

效果展示

实际应用场景 :毛玻璃效果,希望有渐变边框的同时,内层也是渐变背景(需要透最外面的背景色)

解决

border-image 方案❌

/* 这个方法不行 */

直接用 border-image会破坏圆角效果:border-imageborder-radius是互斥的

javascript 复制代码
.element {
  border: 1px solid;
  border-image: linear-gradient(...) 1;
  border-radius: 22px; /* 这个会失效! */
}

伪元素和CSS mask✔

html 复制代码
<!-- template -->
<div class="wrap">
    <div class="content">
        test
    </div>
</div>
javascript 复制代码
// css
.wrap {
    position: relative;
    border-radius: 22px;

    /* 用伪元素实现边框 */
    &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        border-radius: 22px;
        padding: 0.55px; /* 边框宽度 */
        background: linear-gradient(
            180deg,
            rgba(255, 255, 255, 0.3) 0%,
            rgba(255, 255, 255, 0.06) 100%
        );
        
		/* 关键:mask技术实现"边框挖空"效果 */
        mask:
            linear-gradient(#fff 0 0) content-box,
            linear-gradient(#fff 0 0);
        -webkit-mask-composite: xor;
        mask-composite: exclude;
        pointer-events: none;
        z-index: 0;
    }

    /* 内容区域在伪元素之上 */
    & > * {
        position: relative;
        z-index: 1;
    }
}

/* 内层内容区域 */
.content {
    background: linear-gradient(
        180deg,
        rgba(255, 255, 255, 0.1) 0%,
        rgba(255, 255, 255, 0.02) 100%
    );
}
  1. 伪元素的妙用

    使用 ::before伪元素专门负责边框绘制

    主元素保持透明,不干扰背景显示,伪元素的层级在内容之下(z-index: 0)

  2. mask

    它的工作原理:

    创建两个相同的蒙版

    第一个蒙版覆盖 content-box(内容区域)

    第二个蒙版覆盖整个元素

    使用 xor运算,实现"挖空"效果,只保留边框区域

相关推荐
用户059540174464 分钟前
把AI长期记忆测试从手动验证换成pytest,2天揪出11个隐藏Bug
前端·css
lichenyang4531 小时前
从 Vite 空项目到 AIGC 图片工作台:我如何打通生图、任务轮询、生成库与 Canvas 动态特效
前端·人工智能
泡沫冰@1 小时前
上章节中文件的讲解
前端·网络·nginx
进击的丸子2 小时前
APP人脸识别增值版Harmony Demo实操与关键代码解析
前端·程序员·harmonyos
a1117762 小时前
唯美花朵风格的黑胶唱片音乐播放器
前端·css·css3
Hilaku2 小时前
工作 5 年后,决定你薪资上限的究竟是什么?
前端·javascript·程序员
爱分享的程序猿-Clark2 小时前
【前端分享】vue3 有 keep-alive属性吗?
前端
Revolution612 小时前
页面更新后为什么出现 Loading chunk failed:旧页面如何请求了已删除的构建产物
前端·面试·前端工程化
JavaGuide3 小时前
GitHub 9.8 万 Star!把整个代码仓库变成知识图谱,这个 AI Coding 工具太适合 Claude Code / Codex 了
前端·后端·ai编程
hunterandroid3 小时前
[鸿蒙从零到一] HarmonyOS 通知与提醒实战:消息发布、点击跳转与定时触达
前端