如何在保留长宽比的同时使SVG元素扩展以填充容器的宽度

时间:2018-07-19 07:49:52

标签: html css svg

我一直在尝试缩放SVG以适合容器而不使用固定的像素值。从我在网上阅读的内容来看,这应该是可能的,但是我还没有设法使它起作用。一些示例代码如下所示。关于如何获取examplesvg svg元素以填充svgcontainer div宽度的任何建议(仅通过使用HTML和CSS)?提前致谢。

body {
background: rgb(17,17,17);
}

.svgcontainer {
width: 400px;
height: 300px;
background: green;
position: relative;
}

#examplesvg {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
<div class="svgcontainer">
<svg><use xlink:href="#examplesvg"></use></svg>
</div>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<symbol id="examplesvg" viewBox="0 0 303 103" preserveAspectRatio="xMidyMid">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" /> 
</symbol>
</defs>
</svg>

编辑:更新了标题以使预期的行为更清晰。

2 个答案:

答案 0 :(得分:2)

我认为您的CSS选择器是错误的。您不想缩放符号 #example-svg,而是想缩放svg中的.svgcontainer元素。您正在寻找这样的东西吗?

其他注意事项:

  • 您无需指定preserveAspectRatio="xMidYMid";等同于默认值(有关详细信息,请参见MDN/SVG/Attribute/preserveAspectRatio)。
  • 您有错字:preserveAspectRatio="xMidyMid"; y应该是大写的。 SVG在这方面非常挑剔。您很幸运,因为它也是默认设置。 (有些东西很难学;))
  • 应该为viewBox="-1.5 -1.5 303 103",因为SVG边框在图形的内部绘制了一半,在图形的外部绘制了一半。

body { background: grey; }

.svgcontainer {
  width: 400px;
  height: 300px;
  background: green;
  position: relative;
}

.svgcontainer > svg {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
<div class="svgcontainer">
  <svg><use xlink:href="#examplesvg"></use></svg>
</div>

<svg style="display:none">
  <defs>
    <symbol id="examplesvg" viewBox="-1.5 -1.5 303 103">
      <rect width="300" height="100"
        style="fill:blue;stroke-width:3;stroke:black" /> 
    </symbol>
  </defs>
</svg>

答案 1 :(得分:1)

@zenoArrow,请检查以下工作片段以解决您面临的已解决问题。

让我解释一下,出了什么问题:

  1. widthheight设置为div svgcontainer中的svg。使其完全缩放(如果未提及)会将viewBox="0 0 300 100"的宽度和高度设置为svg
  2. 不要使用preserveAspectRatio="xMidyMid"来代替preserveAspectRatio="none"来按父容器缩放/填充svg,如果不添加,它将水平缩放而不是垂直缩放。
  3. viewBox="0 0 303 103"应该等于<rect width="300" height="100",但这也取决于您的要求。

body {
  background: rgb(17, 17, 17);
}

.svgcontainer {
  width: 400px;
  height: 300px;
  background: green;
  position: relative;
}

.example-svg {
  width: 100%;
  height: 100%;
}
<svg style="display: none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <symbol id="examplesvg" viewBox="0 0 300 100" preserveAspectRatio="none">
      <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
    </symbol>
  </defs>
</svg>

<div class="svgcontainer">
  <svg class="example-svg">
    <use xlink:href="#examplesvg"></use>
  </svg>
</div>