为什么这些线不在它们的 svg 元素内?

Why are these lines not inside their svg elements?

我对 svg 还很陌生,需要一些帮助来弄清楚为什么我的线条没有按预期显示。我用红色表示第一行的位置,用蓝色表示 svg 元素所在的位置 - 模仿您在开发人员工具中将鼠标悬停在元素上时看到的内容。我希望该行位于 svg 元素内的某个位置。相反,它显然不是而且是不可见的。第二行是部分可见的,但不是我想要的地方(在下一行的另一个 svg 中,"payer duration" 与另一行相似,很好地居中等)。

代码:

.durationLegend {
  height:45px;
  width:175px;
  border: #cccccc 1px solid;
  fill: none;
}

.durationLegend p {
  margin-top: 2px;
  margin-bottom: 2px;
}

.legendKey {
  height: 10px;
  width: 30px;
}
<div class="durationLegend">
        <p>
            <svg class="legendKey"><line y1="-0.3em" x1="-0.5em" y2="-0.3em" x2="0.75em" stroke-width="3" stroke-dasharray="none" stroke="Green"></line></svg>
            Duration (secs)
        </p>
        <p>
            <svg class="legendKey"><line y1="0.7em" x1="-0.5em" y2="0.7em" x2="0.75em" stroke-width="3" stroke-dasharray="3px, 3px" stroke="Green"></line></svg>
           Payer Duration (secs)
        </p>
    </div>

我认为这是因为你使用了负的 x 和 y 值。

<div class="durationLegend">
    <p>
        <svg class="legendKey"><line y1="0.3em" x1="0.5em" y2="0.3em" x2="0.75em" stroke-width="3" stroke-dasharray="none" stroke="Green"></line></svg>
        Duration (secs)
    </p>
    <p>
        <svg class="legendKey"><line y1="0.7em" x1="-0.5em" y2="0.7em" x2="0.75em" stroke-width="3" stroke-dasharray="3px, 3px" stroke="Green"></line></svg>
       Payer Duration (secs)
    </p>
</div>

这对我有用。

您应该为您的 SVG 定义一个 viewbox,它将确定 SVG

的坐标 space

The viewBox attribute allows to specify that a given set of graphics stretch to fit a particular container element.

The value of the viewBox attribute is a list of four numbers min-x, min-y, width and height, separated by whitespace and/or a comma, which specify a rectangle in user space which should be mapped to the bounds of the viewport established by the given element, taking into account attribute preserveAspectRatio.

如果您在 viewbox space 之外定义元素的开始/结束点,它们将被视为溢出 SVG,但视图框将隐藏该部分,如 overflow:hidden

如果您没有定义 viewbox 元素将具有与给定宽度相同的大小。

基本上,您已经告诉 SVG 'sub-elements' 在 SVG“window”之外开始和/或结束。

有用的文章和教程http://tutorials.jenkov.com/svg/index.html