moys
moys

Reputation: 8033

How to scale SVG to fit the div

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

https://codesandbox.io/s/festive-wing-9f985w?file=/src/Icon.js

What I have

enter image description here

What I would like

enter image description here

How do I achieve this? Please let me know.

Upvotes: 1

Views: 504

Answers (2)

enxaneta
enxaneta

Reputation: 33024

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 class="App">
  <div class="container">
    <div><svg xmlns="http://www.w3.org/2000/svg" class="Icon" 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 class="Text">Start editing to see some magic happen!</h2>
  </div>
  <div class="container">
    <div><svg xmlns="http://www.w3.org/2000/svg" class="Icon" viewBox="0 0 500 500">
        <use href="#mg"/>
      </svg></div>
    <h2 class="Text">Start editing to see some magic happen! if the magic does not happen, keep editing</h2>
  </div>
  <div class="container">
    <div><svg xmlns="http://www.w3.org/2000/svg" class="Icon"  viewBox="0 0 500 500">
        <use href="#mg"/>
      </svg></div>
    <h2 class="Text">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>

Upvotes: 2

A.Amayreh
A.Amayreh

Reputation: 120

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

Upvotes: -1

Related Questions