css - 在 url('data:image/svg+xml') 中使用 CSS 变量
问题描述
我使用以下方法在 div 周围实现虚线边框:
div {
width: 100px;
height: 100px;
border-radius: 16px;
background-image: url('data:image/svg+xml,%3csvg stroke="black" width="100%25" height="100%25" xmlns="http://www.w3.org/2000/svg"%3e%3crect width="100%25" height="100%25" fill="none" rx="16px" ry="16px" stroke-width="6" stroke-dasharray="5%25%2c 2%25" stroke-dashoffset="4" stroke-linecap="butt"/%3e%3c/svg%3e');
}
<div></div>
是否可以用 CSS 变量替换stroke
颜色?black
不幸的是,以下方法不起作用:
div {
--color: black;
background-image: url('data:image/svg+xml,%3csvg stroke="var(--color)" width="100%25" height="100%25" xmlns="http://www.w3.org/2000/svg"%3e%3crect width="100%25" height="100%25" fill="none" rx="16px" ry="16px" stroke-width="6" stroke-dasharray="5%25%2c 2%25" stroke-dashoffset="4" stroke-linecap="butt"/%3e%3c/svg%3e');
}
解决方案
使用面具做不同的事情:
.box {
width: 100px;
height: 100px;
display:inline-block;
position:relative;
}
.box::before {
content:"";
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
-webkit-mask: url('data:image/svg+xml,%3csvg stroke="black" width="100%25" height="100%25" xmlns="http://www.w3.org/2000/svg"%3e%3crect width="100%25" height="100%25" fill="none" rx="16px" ry="16px" stroke-width="6" stroke-dasharray="5%25%2c 2%25" stroke-dashoffset="4" stroke-linecap="butt"/%3e%3c/svg%3e');
background:var(--c,red);
border-radius: 16px;
}
<div class="box"></div>
<div class="box" style="--c:green"></div>
<div class="box" style="--c:blue"></div>
推荐阅读
- entity-framework - 在 where 子句中使用 COALESCE 的 Linq to SQL 查询
- sql - 带有 CASE 语句的 SQL BETWEEN
- swift - 使用 Swift 协议和扩展覆盖对象方法
- html - Safari:是否有针对 Safari CSS 打印定位错误的解决方法?
- java - H2 数据库备份还原序列已存在异常
- c# - java.lang.String 不能以 xamarin 形式转换为 java.lang.Integer 首选项
- swift - ForEach 中的 If 语句导致 Swift 编译错误
- c++ - 使用带有基类指针的 new 创建派生类对象
- python - 如何根据一列中的十六进制代码为 seaborn 绘图着色?
- ios - 使用 React Native 和 Swift 将定义的语言传递给 mapbox 导航类