Home > OS >  How to scale SVG to fit the div
How to scale SVG to fit the div

Time:02-24

I want to use the same SVG on different DIV's. However, I would like the SVG to uniformly scale to it the div.

CodeSandbox link to the working example of what I have is below

enter image description here

What I would like

enter image description here

How do I achieve this? Please let me know.

CodePudding user response:

You will need to remove the width and height attributes of the svg elements, calculate the height of each conteiner and set the width of the svg iqual to the height of the conteiner. This works since the icon is square (see viewBox="0 0 500 500")

//all containers
let cc = document.querySelectorAll(".container");
cc.forEach((c) => {
  //get the height of each container
  let height = c.getBoundingClientRect().height;
  //get the svg element inside each conteiner
  let svg = c.querySelector("svg");
  //set the width of the svg element
  svg.style.width = height;
});
body {
  margin: 0.15rem;
  padding: 0.15rem;
}

.App {
  font-family: sans-serif;
  text-align: center;
}

.container {
  display: flex;
  align-items: center;
  border: 1px solid brown;
  border-radius: 0.25rem;
  margin: 0.15rem;
  padding: 0.15rem;
}

.Text {
  display: inline-block;
  margin: 0.15rem;
  padding: 0.15rem;
}
<div >
  <div >
    <div><svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 500 500">
        <path fill="none" id="mg" stroke="#000" stroke-width="36" stroke-linecap="round" d="m280,278a153,153 0 1,0-2,2l170,170m-91-117 110,110-26,26-110-110"></path>
      </svg></div>
    <h2 >Start editing to see some magic happen!</h2>
  </div>
  <div >
    <div><svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 500 500">
        <use href="#mg"/>
      </svg></div>
    <h2 >Start editing to see some magic happen! if the magic does not happen, keep editing</h2>
  </div>
  <div >
    <div><svg xmlns="http://www.w3.org/2000/svg"   viewBox="0 0 500 500">
        <use href="#mg"/>
      </svg></div>
    <h2 >Start editing to see some magic happen! if the magic does not happen, keep editing. Even after typing nothing happens, you need to just give u ;-)</h2>
  </div>
</div>

Observation: since you are using the same icon, instead of repeating the code for the magnifying glass you can give the path an id (id="mg") and reuse it with <use>

CodePudding user response:

You can save the SVG inside an .svg file and use img element to reference that tag (e.g. src="icon.svg"), this will give more flexibility in scaling the SVG

For more details see: How to Scale SVG

Note: I think it will look better if you align the icon top instead of scaling the icon

  • Related