# Preserving text size when scaling SVGs

DevFeed: [Preserving text size when scaling SVGs](<https://devfeed.tech/articles/preserving-text-size-when-scaling-svgs-37331.md>)

Original publisher: [Read original article](<https://muffinman.io/blog/preserving-text-size-when-scaling-svgs/>)

Author: Stanko

Published: 2025-06-03T00:00:00Z

Content type: tutorial

Language: en

Sources: [Stanko Tadić](<https://devfeed.tech/sources/stanko-tadic.md>)

Topics: [SVG](<https://devfeed.tech/topics/svg.md>), [CSS](<https://devfeed.tech/topics/css.md>), [JavaScript](<https://devfeed.tech/topics/javascript.md>)

## AI overview

The article explains how to keep SVG text at a consistent visual size while the SVG is resized. It uses a CSS variable and ResizeObserver-based JavaScript to counteract the SVG's scale factor.

## Source excerpt

SVGs support non-scaling strokes using the vector-effect attribute, which we can even use to draw non-scaling rectangles and circles. For example, in graphs and charts, text can become too small or too large, so it would be really nice to make it non-scaling. But unfortunately, there is no native solution - text will always scale together with the SVG. We can manually define different font sizes on different breakpoints, but text is still going to be scaled within a single breakpoint. If we need truly non-scalable text, we'll have to use JavaScript. Luckily, not a lot of it - ten lines will do. But before we dive into the solution, here is an example for you (try resizing the wrapper): Hello World!I'll stay 16px on all screen sizes How it works # The idea is to use a CSS variable and a resize observer to counteract SVG scaling. The variable stores the information about how much the SVG is scaled compared to its natural size. Then we can set a resize observer on our SVG, and every time it is resized, we update the CSS variable. That will ensure the font size remains consistent. In order for the CSS variable to have an effect, we have to define font size like thisYou can also use rem or other font size units, as well as media or container queries.: text { font-size: calc(16px * var(--text-factor)); } This means that if we want to keep the font size 16px, and the SVG is rendered at twice its natural size, --text-factor has to be set to 2. To achieve this, we need to divide rendered width by natural width. Let's see how we can get these values. The rendered width is directly accessible as svg.clientWidth. Natural width is a bit trickier, but we can use viewBox to get it. In general, I think it is a good practice to define viewBox on SVGs. View box is a string consisting of four numbers. The third number represents the width of the SVG. We need to parse the string to get the widthIf you don't have viewBox defined, you'll have to update this line to fit your needs.: svg.g