在 url('data:image/svg+xml') 中使用 CSS 变量 [英] Use CSS variable in url('data:image/svg+xml')

查看:42
本文介绍了在 url('data:image/svg+xml') 中使用 CSS 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下内容来实现 div 周围的虚线边框:

I use the following to achieve a dashed border around a 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 ?不幸的是,以下方法不起作用:

Is it possible to replace the stroke color black with a CSS variable? Unfortunately, the following does not work:

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');
}

推荐答案

使用掩码做不同的事情:

Do it differently using mask:

.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>

这篇关于在 url('data:image/svg+xml') 中使用 CSS 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆