为什么不使用 CSS 的“width"属性缩放 SVG 图像? [英] Why don’t SVG images scale using the CSS “width” property?
问题描述
我正在建立一个投资组合网站.
HTML 代码
<div id = "社交"><img src = "linkedin.svg">
CSS 代码(使用 SASS)
#hero {显示:弹性;弹性方向:列;对齐内容:居中;对齐项目:居中;高度:300px;#社会的 {宽度:50%;显示:弹性;对齐内容:间隔;flex-wrap: 包裹;图片{宽度:2em;}}}
问题是我无法使用 CSS width
属性调整 SVG 的大小.这是我在不同情况下获得的结果:
img { 宽度:2em;}
img { 宽度:3em;}
img { 宽度:em;}
请注意图标如何向 hero
div 的中间折叠.
相反,如果我使用 CSS height
属性:
img { 高度:2em;}
img { 高度:3em;}
img { 高度:4em;}
这种行为正是我所需要的,但我不确定这是正确的方式.为什么会发生这种情况?您知道调整 SVG 图像大小的更好方法吗(尤其是使用 flexbox 模型)?
SVG 与位图图像(例如 PNG 等)不同.如果 SVG 具有 viewBox
- 正如您的那样 - 那么它将缩放以适合其定义的视口.它不会像 PNG 那样直接缩放.
因此,如果高度受到限制,增加 img
的 width
不会使图标变得更高.你最终会得到 img
水平居中在一个更宽的盒子里.
我相信你的问题是你的 SVG 定义了一个固定的高度.打开 SVG 文件并确保它们:
- 没有定义
width
和height
,或者 - 将
width
和height
都设置为"100%"
.
那应该可以解决您的问题.如果没有,请将您的 SVG 之一发布到您的问题中,以便我们了解它是如何定义的.
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; }
img { width: 3em; }
img { width: em; }
Please note how icons collapse toward the middle of the hero
div.
Instead, if I use the CSS height
property:
img { height: 2em; }
img { height: 3em; }
img { height: 4em; }
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)?
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:
- have no
width
andheight
defined, or - have
width
andheight
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.
这篇关于为什么不使用 CSS 的“width"属性缩放 SVG 图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!