Search code examples
cssvue.jssvg

Is there a way to scale an inline SVG from outside the <svg> tag?


I'm using a Ruby gem called rqrcode to generate a QR code as an SVG, and then sending it as an API response. In the frontend (Vue.js), I need to display the SVG at a specified size.

Right now my code looks like this, and while it does render the SVG, I can't specify the size.

<div v-html="qrCode" />

I tried adding styles to the div, but the SVG disregards it completely. To give you an idea, this it what it looks like:

div and svg

My understanding is that you can scale SVGs using width, height and viewBox inside the <svg> tag. However, there's no way to specify those properties in rqrcode - the height and width are decided by the gem, and the opening svg tag looks like this:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" width="246" height="246" shape-rendering="crispEdges">

So my question is, how can I specify the size of the inline SVG to fit inside the parent container, from the parent container?

[Edit for clarification] If the dimensions in the <svg> tag are larger than my div container, I'd like for the svg to shrink to fit the container. And vice versa - if the dimensions are smaller, I want the svg to expand ot fit the container. I'm not sure if this is possible.


Solution

  • You can actually override the inline height and width using css.

    Note that the css needs to be NOT scoped, so create another style block if required.

    <style scoped>
      ...
    </style>
    <style>
    div > svg {
      height: 100px;
      width: 100px;
    }
    </style>