How to centre this SVG word

79 views Asked by At

Trying to figure out how to centre this SVG text horizontally and vertically in the viewport (The element needs to remains central across different viewport sizes)

Tried using the viewbox panning but I can't get everything aligned - part of the SVG remains cut off/incorrectly scaled

Also looking to set the font size to the same rem value as other standard text elements on the page.

SVG text is used as there's a 'slice' GSAP animation happening to it.

<div class="stage">
<svg id="demo" xmlns="http://www.w3.org/2000/svg" width="2000" height="800" viewBox="0 0 1000 800">
<defs>
  <pattern id="slicePattern" patternUnits="userSpaceOnUse" width="3000" height="800" x="0" y="0"><text transform="translate(500 400)" text-anchor="middle" font-size="220" fill="#fff">SLICE</text>
  </pattern>
</defs>

<g fill="url(#slicePattern)">
  <polygon id="slide1" points="0,150 551,150 201,400 0,400" />
  <polygon id="slide2" points="549,150 1000,400 999,400 1000,150" />
  <polygon points="200,400 550,150 1000,400" />
</g>
  
<line x1="550" y1="150" x2="200" y2="400" stroke-width="1" stroke="white"/>
<line x1="550" y1="150" x2="1000" y2="400" stroke-width="1" stroke="white"/> 

  </svg>
</div>

The standard text to match to is 2.5em. Setting the SVG text to that it doesn't size the same. Also can't correctly pan the viewbox to centre the svg text in the viewport. I need this to be responsive centering also.

In short, I don't understand the effect the text transform properties are having on the element, or how this relates to the viewport/viewbox values.

1

There are 1 answers

1
BehRouz On

For making the whole svg responsive:

svg{
    width:100%;
    height:auto
}

For the text, It has already text-anchor set to middle which is correct. You need to specify the position of the text by setting x and y values.

<text text-anchor="middle" x="50" y="0">The Text</text>

The font-size in svg has nothing to do with the default font-size of the css. It's relative to the viewBox of your svg. SVG functions as a separate image file. But you can have access to its style attributes by css.