2016-08-20 54 views
10

我正在建立一个投资组合网站。为什么我的SVG图像不能使用CSS“width”属性进行缩放?

HTML代码

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

CSS代码(使用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; 
     } 
    } 
} 

的问题是,我不能使用CSS width属性来调整SVGs。以下是我在不同情况下获得:

img { width: 2em; }

enter image description here

img { width: 3em; }

enter image description here

img { width: em; }

enter image description here

请注意图标如何向hero div中间折叠。

相反,如果我使用的CSS属性height

img { height: 2em; }

enter image description here

img { height: 3em; }

enter image description here

img { height: 4em; }

enter image description here

这种行为是我需要的,但我不确定这是正确的方法。为什么会发生?您是否知道调整SVG图像尺寸的更好方法(特别是使用flexbox型号)?

+1

@Michael_B,谢谢,我的错误。 – harpo

回答

18

SVGs比位图图像,例如PNG等不同如果SVG具有viewBox - 作为你的出现 - 那么它将被缩放以适合它的定义视口。它不会像PNG那样直接缩放。

因此,如果高度受到限制,增加imgwidth将不会使图标更高。你只需要以更宽的方框水平居中即可。

我相信你的问题在于你的SVG在其中定义了一个固定的高度。打开了SVG文件,并确保他们要么:

  1. 没有width和定义height,或
  2. widthheight都设置为"100%"

这应该可以解决您的问题。如果没有,请将其中一个SVG发布到您的问题中,以便我们看到它是如何定义的。

+0

你的答案似乎是解决我的问题。所以,如果我没有指定SVG的'width'和'height',我想我可以在没有问题的情况下进行缩放。 –