user519477
user519477

Reputation:

How to center text and scale font size based on container using SVG?

For a responsive website, I am trying to center a text and scale its font-size using SVG so that I don't need to do any calculations with JavaScript.

My first problem is that I tried using x="50%" and y="50%" with text-anchor="middle" and alignment-baseline="central" but while this works in Chrome, in IE, Edge and Firefox the text is not vertically centered, but its baseline is so that the text itself is slightly too high. How can I center the text vertically in those browsers too without having a fixed height?

My second problem is scaling. What I found so far on the Internet is using lengthAdjust="spacingAndGlyphs" but that gives weird results with the text appearing stretched. How can I scale everything just like an image would be scaled?

Here is my starting pen: https://codepen.io/smares/pen/QMVPvN

I also read about viewBox, but I don't fully understand how to use that given I have no container with fixed sizes.

I have to use inline SVG because the text is actually generated by Vue.

Upvotes: 3

Views: 4772

Answers (1)

Mehdi
Mehdi

Reputation: 7403

Vertical alignment

For the vertical alignment issue, problem is caused by the fact that aligment baseline is not supported in Firefox. You may refer to this answer to a similar question:

Unfortunately, although this is the "correct" way of achieving what you're after it would appear Firefox have not implemented a lot of the presentation attributes for the SVG Text Module ('SVG in Firefox' MDN Documentation)

Edit (thanks @Robert Longson): dominant-baseline is supported, on the other hand (MDN article), and seems to achieve the same.

Scaling

For the scaling, using preserveAspectRatio="xMinYMin" and viewBox will let the SVG (and its text) scale correctly, without being stretched. You may set the SVG's width and height to 100%, or to other dimensions...

<svg preserveAspectRatio="xMinYMin" viewBox="0 0 800 450" width="100%" xmlns="http://www.w3.org/2000/svg">

N.B. Using 100% to set the SVG's size does not produce the appropriate results in IE11, possibly also in Edge. A dimension in pixels works well, as far as I recall.

The article "How to scale SVG" from CSS Tricks is pretty clear and complete to understand the different concepts.

Updated codepen

Here is the updated pen, with dominant-baseline set, as well as the scaling attributes. Resize the window to see the SVG size's being updated accordingly.

Upvotes: 1

Related Questions