Search code examples
htmlcsssvginkscapeinline-svg

Setting the Viewbox so that the inline SVG will “Snap” to the size of the containing element?


I created this simple inline SVG by saving as "Optimized SVG" in inkscape. Prior to saving I set the size to 200X200px.

<div style="width: 200px; background-color: red;">
          <?xml version="1.0" encoding="UTF-8"?>
        <svg viewBox="0 0 200 200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
         <g>
          <path class="fs-logo-fill" d="m71.679 40.782v52.917h52.917v-52.917zm26.458 7.2166a19.242 19.242 0 0 1 19.242 19.242 19.242 19.242 0 0 1-19.242 19.242 19.242 19.242 0 0 1-19.242-19.242 19.242 19.242 0 0 1 19.242-19.242z"/>
         </g>
        </svg>

I then put it inside a the div element seen that has a width of 200px.

This is the codepen:

https://codepen.io/oleersoy/pen/dLxvEJ

As can be seen the red div is a lot larger than the inline svg rendering. How do we set the viewbox parameters so that the inline SVG will always fit the size of the containing element?


Solution

  • In order to get the viewBox right you need to get the size of the bounding box of the path, and use the values you get to define the viewBox.

    console.log(thePath.getBBox())
    <div style="width: 200px; background-color: red;">
              
            <svg viewBox="71.68 40.782 52.92 52.92" style="display:block;">
             <g>
              <path id="thePath" class="fs-logo-fill" d="m71.679 40.782v52.917h52.917v-52.917zm26.458 7.2166a19.242 19.242 0 0 1 19.242 19.242 19.242 19.242 0 0 1-19.242 19.242 19.242 19.242 0 0 1-19.242-19.242 19.242 19.242 0 0 1 19.242-19.242z"/>
             </g>
            </svg>
    </div>

    In this case the bounding box of the path is:

    let BB = {
      "x": 71.67900085449219,
      "y": 40.78200149536133,
      "width": 52.91699981689453,
      "height": 52.9170036315918
    }
    

    The viewBox will have this aspect:

    viewBox=`${BB.x} ${BB.y} ${BB.width} ${BB.height}`