SVG 精灵与 <use> CSS 中的 xlink ::after



我在正文中使用了这样的SVG精灵:

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
    <symbol id="bars" width="1792" height="1792" viewBox="0 0 1792 1792">
        <path d="M1664 1344v128q0 26-19 45t-45 19h-1408q-26 0-45-19t-19-45v-128q0-26 19-45t45-19h1408q26 0 45 19t19 45zm0-512v128q0 26-19 45t-45 19h-1408q-26 0-45-19t-19-45v-128q0-26 19-45t45-19h1408q26 0 45 19t19 45zm0-512v128q0 26-19 45t-45 19h-1408q-26 0-45-19t-19-45v-128q0-26 19-45t45-19h1408q26 0 45 19t19 45z"/>
    </symbol>
</svg>

如果我需要这个符号,我可以这样命名它:

<svg class="icon left bars" style="fill: #000;">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#bars"></use>
</svg>

现在我需要这个SVG在CSS ::after。我知道你可以在::after中使用SVG作为背景图像,但它不会使用:

.element::after {
  background: url('data:image/svg+xml;utf8,<svg class="icon left bars" style="fill: #000;"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#bars"></use></svg>') no-repeat;
  //background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='61' height='41' fill='#000' stroke='none'><path d='M0,0 6,10 L12,0 L0,0 Z'></path></svg>") no-repeat;
  content: "";
  display: block;
  height: 16px;
  width: 16px;
}

演示:JSFiddle

有人让这个工作吗?

.element::before	{background-image:url("data:image/svg+xml;charset=UTF-8,<svg xmlns='http://www.w3.org/2000/svg' width='100%' height='100%' viewBox='0 0 75.33 68.119'> <polygon fill-rule='evenodd' clip-rule='evenodd' fill='red' points='8.125,11.865 75.33,0 73.794,37.574 70.938,68.119 0,64.603 '/> </svg>"); content:""; display:inline-block; width:75.33px; height:68.119px;}
<div class="element"></div>

然而,它只能在非ie浏览器上工作,遗憾的是,你可以把它变成一个mixin在less/sass,这样你就不会膨胀你的工作css。

我从https://codepen.io/AmeliaBR/details/xijuv也值得一读https://manu.ninja/inline-svg-how-i-learned-to-stop-worrying-and-love-gzip/

EDIT在ie11中工作在IE背景图片的URL参数中使用原始svg

最新更新