How to Scale an SVG with CSS Only

Blog

Posted by Nuno Marques on 23 Aug 2021

Tutorial

To scale an SVG with CSS only, follow these simple steps:

  1. Set a class (.scaling-svg) on your HTML container element.
  2. Remove all other attributes from the <svg> element except viewBox.
  3. Add the following CSS rules for the .scaling-svg class:
<div class="scaling-svg">
  <svg viewBox="0 0 60 55">
    <path
      d="M30,50 C45,50 55,45 55,35
        Q 55,27 50,25 C55,22 53,15 45,20
        S 23,25 15,20 S5,22 10,25
        Q 5,27 5,35 C5,45 15,50 30,50Z"
    />
  </svg>
</div>
.scaling-svg {
  height: 0;
  padding: 0;
  padding-bottom: 100%; /* Maintain aspect ratio */
  position: relative;
  width: 100%;
}

Explanation

  • The .scaling-svg class is applied to the container <div> element, which wraps the SVG.
  • The SVG element only retains the viewBox attribute, allowing it to scale proportionally.
  • CSS rules for .scaling-svg set the height to 0 and use padding-bottom to maintain the aspect ratio based on the container's width.
  • The position: relative; and width: 100%; properties ensure the SVG scales appropriately within its container.

Result

Resize your browser's window to see the magic happening. Check out the result on CodePen

This post was tagged in: