SVG作为背景图像没有出现

时间:2017-09-14 05:19:26

标签: css svg background-image scale

我已尝试过我在网上找到的常用解决方案,但无法获得 要出现的背景图片。

在第一个标题中,SVG图像似乎比其viewBox推出的容器要远得多。在第2个标题中,背景图像根本不显示。 (SVG代码相同)

HTML:



header {
  margin: 1rem auto 0 auto;
  border: 1px solid red;
}

.container {
  border: 2px dotted orange;
}

.container svg {
  border: 1px dashed blue;
  width: 100%;
  height: 100%;
}

#inline-svg {
  border: 2px dashed pink;
}

#header1 {}

#header2 {
  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' id='background-svg' width='400px' height='200px' viewBox='0 0 400px 200px'>
 <ellipse cx='200' cy='100' rx='200' ry='100' fill='green' /> </svg>");
 background-size: auto auto;
}

#background-svg {
  border: 3px solid black;
}
&#13;
<header id="header1" class="masthead">
  <div id="1st-container" class="container">
    <svg xmlns='http://www.w3.org/2000/svg' id='inline-svg' width='200px' height='100px' viewBox='0 0 200px 200px'>
      <ellipse cx='200' cy='100' rx='200' ry='100' fill='green' />
    </svg>
  </div>
</header>

<header id="header2" class="masthead">
  <div id="2nd-container" class="container">
    hello
  </div>
</header>
&#13;
&#13;
&#13;

https://jsfiddle.net/abalter/c4fmou2n/

1 个答案:

答案 0 :(得分:2)

当你在url中添加svg代码时请不要破坏它,否则它无法正常工作。

header {
  margin: 1rem auto 0 auto;
  border: 1px solid red;
}
.container {
  border: 2px dotted orange;
}
.container svg {
  border: 1px dashed blue;
  width: 100%;
  height: 100%;
}
#inline-svg {
  border: 2px dashed pink;
}
#header1 {}
#header2 {
  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' id='background-svg' width='400px' height='200px' viewBox='0 0 400px 200px'><ellipse cx='200' cy='100' rx='200' ry='100' fill='green' /> </svg>");
  background-size: auto auto;
}
#background-svg {
  border: 3px solid black;
}
<header id="header1" class="masthead">
  <div id="1st-container" class="container">
    <svg xmlns='http://www.w3.org/2000/svg' id='inline-svg' width='200px' height='100px' viewBox='0 0 200px 200px'>
      <ellipse cx='200' cy='100' rx='200' ry='100' fill='green' />
    </svg>
  </div>
</header>

<header id="header2" class="masthead">
  <div id="2nd-container" class="container">
    hello
  </div>
</header>