DEV Community

Cover image for My 2 most frequently used SVG features
Andreas Riedmüller
Andreas Riedmüller

Posted on • Updated on

My 2 most frequently used SVG features

I use editors like Figma or Sketch to edit and export SVG. But there are two SVG features I find myself adding to the exported SVG markup quite often.

1. Stretch SVG with preserveAspectRatio="none"

Unlike rasterized images (like PNG or JPG) SVG graphics won’t be stretched when setting height and width in HTML or CSS. Instead the graphic will be resized to fit inside the set dimensions while keeping its original aspect ratio.

This behavior can be changed however by setting preserveAspectRatio like so:

<svg preserveAspectRatio="none" viewBox="0 0 42 42" >
Enter fullscreen mode Exit fullscreen mode

Note: The viewBox attribute must be defined in order for this to work. When exporting from an editor this is usually done for you. Without a view box the contents of a SVG graphic will always render in the same size on your screen.


Default behavior



With preserveAspectRatio="none"

While none is the only value I ever needed, there are more options available:
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio

2. Consistent stroke width with
non-scaling-stroke

This feature can be very useful if you need a consistent line width between multiple images and/or CSS borders for example.

Just add the value non-scaling-stroke to the vector-effect attribute of an SVG element and the stroke will always render with the same stroke width, no matter how you scale it.

<svg >
<path vector-effect="non-scaling-stroke" stroke-width="2" />
<circle vector-effect="non-scaling-stroke" stroke-width="2" />
</svg>
Enter fullscreen mode Exit fullscreen mode

 


Default behavior



vector-effect="non-scaling-stroke"

More about the vector-effect attribute: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/vector-effect

Do you want more?

Here is another article of mine about using currentColor to set the SVG's color in CSS: Import SVGs as React component and set color in CSS with currentColor


I hope this was worth reading for you. Did you ever use one of these features? Is there some other SVG feature that you find particularly useful?

Top comments (0)