Why don't my SVG images scale using the CSS “w

2020-02-08 06:43发布

I'm building a portfolio website.

HTML Code

<div id = "hero">
   <div id = "social">
      <img src = "facebook.svg">
      <img src = "linkedin.svg">
      <img src = "instagram.svg">
    </div>
</div>

CSS code (using SASS)

#hero {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 300px;

    #social {
        width: 50%;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        img {
            width: 2em;
        }
    }
}

The problem is that I'm not able to resize SVGs using the CSS width property. Here is what I obtain in different cases:

img { width: 2em; }

enter image description here

img { width: 3em; }

enter image description here

img { width: em; }

enter image description here

Please note how icons collapse toward the middle of the hero div.

Instead, if I use the CSS height property:

img { height: 2em; }

enter image description here

img { height: 3em; }

enter image description here

img { height: 4em; }

enter image description here

This behaviour is what I need, but I'm not sure this is the right way. Why this happens? Do you know better ways of resizeing SVG images (especially using the flexbox model)?

标签: html css svg sass
4条回答
我欲成王,谁敢阻挡
2楼-- · 2020-02-08 07:16

I had to figure it out myself but some svgs your need to match the viewport & width+height in.

E.g. if it already has width="x" height="y" then =>

add <svg ... viewport="0 0 [width] [height]">

and the opposite.

After that it will scale with <svg ... style="width: xxx; height: yyy;">

查看更多
甜甜的少女心
3楼-- · 2020-02-08 07:27

You have to modify the viewBox property to change the height and the width correctly with a svg. It is in the <svg> tag of the svg.

https://developer.mozilla.org/en/docs/Web/SVG/Attribute/viewBox

查看更多
Ridiculous、
4楼-- · 2020-02-08 07:29

SVGs are different than bitmap images such as PNG etc. If an SVG has a viewBox - as yours appear to - then it will be scaled to fit it's defined viewport. It won't directly scale like a PNG would.

So increasing the width of the img won't make the icons any taller if the height is restricted. You'll just end up with the img horizontally centred in a wider box.

I believe your problem is that your SVGs have a fixed height defined in them. Open up the SVG files and make sure they either:

  1. have no width and height defined, or
  2. have width and height both set to "100%".

That should solve your problem. If it doesn't, post one of your SVGs into your question so we can see how it is defined.

查看更多
萌系小妹纸
5楼-- · 2020-02-08 07:36

I have the same problem... and I found a simple solution. Just import the SVG image with the follow tool, and export: https://editor.method.ac/

查看更多
登录 后发表回答