【问题标题】:Why does an SVG appear fine in HTML but not when I use it as an background image in CSS? [duplicate]为什么 SVG 在 HTML 中看起来很好,但当我在 CSS 中将它用作背景图像时却不行? [复制]
【发布时间】:2021-05-18 06:44:42
【问题描述】:

我有一个 SVG,我想将其用作 <select> 元素上的图标。

如果我将以下内容单独粘贴到 div 中,它会起作用 - SVG 会呈现并出现。

<svg xmlns='http://www.w3.org/2000/svg' width='15.826' height='9.413' viewBox='0 0 15.826 9.413'><path id='Path_100' data-name='Path 100' d='M175.428,127l6.5,7,6.5-7' transform='translate(-174.015 -125.584)' fill='none' stroke='#000' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'/></svg>

但是,当我将它作为背景图片添加到 CSS 中时,例如:

  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='18.899' height='10.449' viewBox='0 0 18.899 10.449'><path id='Path_5' data-name='Path 5' d='M553.826,51.436l8.035,8.035,8.035-8.035' transform='translate(-553.826 -51.436)' fill='none' stroke='#fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'/></svg>");

它不起作用 - 什么也没有出现。但是,我可以使用 CSS 显示其他 SVG 图标。

我的完整 CSS 类是:

.select1 {
  width: 50%;
  -webkit-appearance: none;
  -moz-appearance: none;
  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='15.826' height='9.413' viewBox='0 0 15.826 9.413'><path id='Path_100' data-name='Path 100' d='M175.428,127l6.5,7,6.5-7' transform='translate(-174.015 -125.584)' fill='none' stroke='#000' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'/></svg>");
  background-repeat: no-repeat;
  background-position-x: 98%;
  background-position-y: 50%;
}

这个小提琴更清楚地说明了我的意思:https://jsfiddle.net/MeltingDog/uhter1f3/12/

为什么 SVG 在 HTML 中看起来很好,但作为背景图片却不行?

【问题讨论】:

标签: html css svg


【解决方案1】:

# 是 URL 中的特殊字符。您的 SVG 在属性中间被stroke='#fff' 截断。

你必须encode它。

.example {
  height: 100px;
  width: 100px;
  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='15.826' height='9.413' viewBox='0 0 15.826 9.413'><path id='Path_100' data-name='Path 100' d='M175.428,127l6.5,7,6.5-7' transform='translate(-174.015 -125.584)' fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='2'/></svg>");
}
&lt;div class="example"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2014-07-01
    • 2021-06-01
    • 2014-02-12
    • 2018-01-10
    • 1970-01-01
    • 2017-03-05
    相关资源
    最近更新 更多