CSS中的SVG图标路径类

问题描述

我将以下 SVG 图标作为 path 嵌入到我的 HTML 页面中:

<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z"/></svg>

如何将上述 SVG 图标 path 作为 class 包含在 CSS 中?所以我可以像这样在我的 HTML 页面中将它用作 attribute

<i class="chevron-right"></i>

更新:关于已接受的答案,我在使图标正确垂直居中时遇到了一些问题,最终找到了更简单的 CSS 代码

.chevron-right {
    vertical-align: middle;
    content: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3e%3cpath fill-rule='evenodd' d='M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
}

解决方法

用作背景:

.chevron-right {
   display:inline-block;
   width:1rem;
   background:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z"/></svg>') 0 0/contain no-repeat;
}

.chevron-right::before {
  content:"";
  display:block;
  padding-top:100%;
}
<i class="chevron-right"></i>
<i class="chevron-right" style="width:2rem"></i>
<i class="chevron-right" style="width:4rem"></i>

如果您想要着色,请考虑遮罩:

.chevron-right {
   display:inline-block;
   width:1rem;
   -webkit-mask:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z"/></svg>') 0 0/contain no-repeat,linear-gradient(#fff 0 0);
   -webkit-mask-composite:destination-in;
   mask-composite:intersect;
   background:currentColor;
}

.chevron-right::before {
  content:"";
  display:block;
  padding-top:100%;
}
<i class="chevron-right"></i>
<i class="chevron-right" style="width:2rem;color:red;"></i>
<i class="chevron-right" style="width:4rem;color:blue;"></i>

,

创建自定义元素:<svg-icon path="your d path"></svg-icon>

<style>
  svg-icon svg {
    width: 80px;
    height:80px;
    background: grey;
  }
</style>

<svg-icon path="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z"></svg-icon>

<script>
  customElements.define("svg-icon",class extends HTMLElement {
    connectedCallback() {
        this.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="${this.getAttribute("path")}"/></svg>`;
    }
  });

</script>

如果您需要图标,请参阅我的宠物项目 IconMeister.github.io