为什么我的SVG图片不使用CSS“宽度"比例缩放财产? [英] Why don’t my SVG images scale using the CSS "width" property?
问题描述
我正在建立一个投资组合网站.
I'm building a portfolio website.
<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
属性来调整SVG的大小.这是我在不同情况下获得的信息:
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; }
img { width: 3em; }
img { width: em; }
请注意图标如何向hero
div的中间折叠.
Please note how icons collapse toward the middle of the hero
div.
相反,如果我使用CSS height
属性:
Instead, if I use the CSS height
property:
img { height: 2em; }
img { height: 3em; }
img { height: 4em; }
这是我需要的行为,但是我不确定这是正确的方法.为什么会这样?您是否知道调整SVG图像大小的更好方法(尤其是使用 flexbox模型)?
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)?
推荐答案
SVG与位图图像(例如PNG等)不同.如果SVG具有viewBox
(如您所见),那么它将被缩放以适合它的定义的视口.它不会像PNG那样直接缩放.
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.
因此,如果限制高度,增加img
的width
不会使图标变高.最后,您将img
水平居中放置在一个较宽的框中.
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.
我相信您的问题是SVG在其中定义了固定的高度.打开SVG文件,并确保它们之一:
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:
- 没有定义
width
和height
,或者 - 将
width
和height
都设置为"100%"
.
- have no
width
andheight
defined, or - have
width
andheight
both set to"100%"
.
那应该可以解决您的问题.如果没有,请将您的SVG之一发布到您的问题中,以便我们了解其定义.
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.
这篇关于为什么我的SVG图片不使用CSS“宽度"比例缩放财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!