2016-08-20 51 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',我想我可以在沒有問題的情況下進行縮放。 –