首页 > 解决方案 > SVG中心横竖线

问题描述

如何创建一个包含两条线(一条水平线,一条垂直线)的 SVG,从一侧的中间到另一侧的中间,从而使加号与 SVG 容器的大小相同?

这就是我现在所拥有的,但是当更改 SVG 大小时,行长不会改变

<svg width="10px" height="10px">
<line class="point" x1="0" x2="10" y1="5" y2="5" />
<line class="point" x1="5" x2="5" y1="0" y2="10" />
</svg>

标签: csssvgwidthline

解决方案


要使 SVG 的内容随其大小缩放,它需要有一个viewBox.

svg {
  background-color: linen;
}

.point {
  stroke: black;
  stroke-width: 1;
}
<svg width="10px" height="10px" viewBox="0 0 10 10">
<line class="point" x1="0" x2="10" y1="5" y2="5" />
<line class="point" x1="5" x2="5" y1="0" y2="10" />
</svg>

<svg width="30px" height="30px" viewBox="0 0 10 10">
<line class="point" x1="0" x2="10" y1="5" y2="5" />
<line class="point" x1="5" x2="5" y1="0" y2="10" />
</svg>

<svg width="100px" height="100px" viewBox="0 0 10 10">
<line class="point" x1="0" x2="10" y1="5" y2="5" />
<line class="point" x1="5" x2="5" y1="0" y2="10" />
</svg>

在此示例中,所有内容都会缩放,包括线宽。如果这不是您想要的,那么您可以使用@SirExotic 的方法(使用百分比坐标),或者您可以使用vector-effect: non-scaling-stroke.

svg {
  background-color: linen;
}

.point {
  stroke: black;
  stroke-width: 1;
  vector-effect: non-scaling-stroke;
}
<svg width="10px" height="10px" viewBox="0 0 10 10">
<line class="point" x1="0" x2="10" y1="5" y2="5" />
<line class="point" x1="5" x2="5" y1="0" y2="10" />
</svg>

<svg width="30px" height="30px" viewBox="0 0 10 10">
<line class="point" x1="0" x2="10" y1="5" y2="5" />
<line class="point" x1="5" x2="5" y1="0" y2="10" />
</svg>

<svg width="100px" height="100px" viewBox="0 0 10 10">
<line class="point" x1="0" x2="10" y1="5" y2="5" />
<line class="point" x1="5" x2="5" y1="0" y2="10" />
</svg>


推荐阅读