【问题标题】:Use CSS variable in url('data:image/svg+xml')在 url('data:image/svg+xml') 中使用 CSS 变量
【发布时间】:2021-07-05 14:03:40
【问题描述】:

我使用以下方法在 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');
}

【问题讨论】:

    标签: css svg css-variables


    【解决方案1】:

    使用面具做不同的事情:

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

    【讨论】:

    • 这真的很酷 - 谢谢!为什么你用::before 做的这么复杂?如果您只是将蒙版和背景应用于原始div,它似乎可以正常工作
    • @TonaldDrump 我考虑到你将有内容的事实。将遮罩应用于主元素将隐藏其中的所有内容
    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多