没有宽度/高度的SVG呈现自然大小 [英] SVG without width/height renders with a natural size
问题描述
我有这个SVG,它没有 width
或 height
属性我有以下HTML
I have this SVG which doesn't have a width
or height
attribute
I have the following HTML
<div class="block">
<img src="https://s3-eu....vAmfIxVv/kiwi.svg">
</div>
使用以下CSS
.block {
display: inline-block;
width: auto;
}
img {
width: 100%;
}
尽管我希望svg的宽度为100%,但它在chrome中呈现的宽度/高度有些奇怪(仅在Firefox中,其尺寸为0x0)
Although I want the svg to be 100% in width, it renders in chrome with some weird width/height (Only in firefox it has a dimensions of 0x0)
那么,这个自然的 width
来自何处,为什么宽度不是100%?
So any suggestions where this natural width
comes from and why isn't the width 100% ?
是否可以将 svg
宽度设置为100%?
Is it possible to make the svg
width 100% ?
推荐答案
如果要在< svg>
元素上设置自动宽度,则只需使用 display:block
在父< div>
上,但在SVG元素本身上使用 max-width:100%
.当SVG包含在inline-block元素中时,Chrome以某种方式无法强制执行正确的宽度计算:
If you want auto width on the <svg>
elements, you should simply use display: block
on the parent <div>
, but use max-width: 100%
on the SVG elements themselves. Chrome somehow fails to enforce proper width calculations when SVGs are contained within an inline-block element:
.block {
display: block;
}
img {
max-width: 100%;
}
概念验证示例:
section {
border: 2px solid green;
margin: 20px;
background-color: yellow;
width: 500px;
height: 500px;
}
.block {
display: block;
}
img {
max-width: 100%;
}
.svg {
border: 1px solid red;
}
<section>
<div class="block svg">
<img src="https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/46194/456229/JCHA4rtvAmfIxVv/kiwi.svg" alt="">
</div>
<div class="block">
<img src="http://placeholder.pics/svg/100x200" alt="">
</div>
</section>
这篇关于没有宽度/高度的SVG呈现自然大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!