SVG圆圈采用任何div大小的所有高度保留方面

时间:2017-11-23 10:22:42

标签: css svg

这个想法是在SVG中绘制一个圆圈,它在父div上占据整个高度,无论父div的大小如何。宽度应该以某种方式被忽略。

我一直在使用SVG的宽高比工作,但这并不适用于所有场景:

<div style='width:400px;height:100px'>  
<svg  width="100%" height="100%" viewbox="0 0 200 100" preserveAspectRatio="xMinYMin slice">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="0" fill="red" />
  <text x="100" y="50">Example SVG text 1</text>
</svg>
</div>

div宽度定义为200px,它正在工作。

小提琴:https://jsfiddle.net/91sp2j0x/11/

3 个答案:

答案 0 :(得分:2)

preserveAspectRatio="none"svg{width:100%}将提供100%调整后的身高。

&#13;
&#13;
svg{
    width: 100%;
}
&#13;
<div style='width:200px;height:100px;overflow:hidden'>
<svg   height="100%" viewbox="0 0 200 100" preserveAspectRatio="none">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="0" fill="red" />
  <text x="100" y="50">200px w: cut text</text>
</svg>
</div>
<div style='width:500px;height:100px;overflow:hidden'>
<svg height="100%" viewbox="0 0 200 100" preserveAspectRatio="none">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="0" fill="red" />
  <text x="100" y="50">500px w: full visible text</text>
</svg>
</div>
<div style='width:50px;height:100px;overflow:hidden'>
<svg height="100%" viewbox="0 0 200 100" preserveAspectRatio="none" >
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="0" fill="red" />
  <text x="100" y="50">100px width : Nothing is visible</text>
</svg>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

50属性指定r的值将允许嵌套的svg元素保持其包含(父)元素的100%高度。

代码段示范:

.resize-demonstration {
  resize: auto;
  border: 1px solid gray;
  box-sizing: border-box;
  overflow:hidden;
}

.container-model {
  border-right: 1px dashed gray;
}
<p>Resize the element below <u>vertically</u> or <u>horzontally</u> to demonstrate the intended behaviour</p>
<p><em>Note:</em> the <code>svg</code> has been wrapped in an containing element for <em>user-friendly resizing</em> (interaction with the resizing icon in the bottom-right corner), this is <strong>only for the sake of demonstration</strong> and should not be considered required.</p>
<div class="resize-demonstration" style="height: 100px">
  <div style='width:50px;height:100%;overflow:hidden;' class="container-model">
    <svg height="100%" viewbox="0 0 200 100" preserveAspectRatio="xMinYMin meet">
      <circle cx="50" cy="50" r="50" stroke="black" stroke-width="0" fill="red" />
      <text x="100" y="50">100px width : Nothing is visible</text>
    </svg>
  </div>
</div>

Updated JSFiddle

答案 2 :(得分:-1)

如果我理解正确,你想拥有高度半径的圆圈...... 我成功地这样做了(如果我明白你的问题是正确的):

    <div style='width:800px;height:120px;'>  
<svg  viewbox="0 -10 200 140" preserveAspectRatio="xMinYMin slice">  /* just remove the height and the width from the svg, it will take the parameters from the div... */ 
  <circle cx="18%" cy="18%" r="18%" stroke="black" stroke-width="0" fill="red" />
  <text x="100" y="50">Example SVG text 1</text>
</svg>
</div>