User1979
User1979

Reputation: 857

How to set svg width and height?

i have a 3 svg icon with different viewBox value.

<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"></svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 16"></svg>
<svg viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg"></svg>

How i can set my svg width and height with same value, so all of these 3 icon will have the same size.

<div>
    <span>
          <svg></svg>
    </span>
</div>

Upvotes: 8

Views: 22724

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101918

All three icons will scale to the same size if you give them the same width and height. The shorter one will centre itself.

svg {
  width: 50px;
  height: 50px;
  border-color: blue;
  background-color: yellow;
}
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
  <rect width="100%" height="100%"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 16">
  <rect width="100%" height="100%"/>
</svg>
<svg viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg">
  <rect width="100%" height="100%"/>
</svg>

If, by "same size", you mean same height. Then just set the height only, and leave the browser to adjust the width based on the viewBox aspect ratio.

svg {
  height: 50px;
  border-color: blue;
  background-color: yellow;
}
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
  <rect width="100%" height="100%"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 16">
  <rect width="100%" height="100%"/>
</svg>
<svg viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg">
  <rect width="100%" height="100%"/>
</svg>

Upvotes: 12

Related Questions