SVG center horizontal and vertical line

For an SVG’s contents to scale with its size, it needs to have a 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>

 Run code snippetExpand snippet

In this example, everything scales, including the line width. If that’s not what you want, then you can either use @SirExotic’s approach (using percentage coordinates), or you could set the lines to not scale by using 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>

 Run code snippetExpand snippet

Leave a Comment