Img src VS CSS背景图片没有内在尺寸 [英] Img src VS CSS Background Image No Intrinsic Dimensions
问题描述
< img src = .../>
成
< img class =image/> //也可以是div,无所谓
并给它一个background-image CSS样式取而代之的是(这是由于webpack捆绑和我在 .md
文件中没有导入和变量)
问题是,第一个选项正确加载图像,而不必指定高度/宽度,第二种方法什么都不显示,除非我指定高度/宽度。
为什么会这样,并且有没有办法绕过这没有指定每个这样的事件的高度/宽度?
最好你可以做的是计算的比例 img
,然后使用 padding
和覆盖
的值来适应:
举例来说,如果图片 1:1
比例:
.image {background-image:url 'http://i.imgur.com/3Zh2iqf.jpg');背景重复:不重复;背景尺寸:盖; padding-top:100%;}
< div> < div class =image> < / div>< / div>
I've got a markdown with HTML built inside and I need to change the following:
<img src="..." />
Into
<img class="image" /> // Could also be a div, doesn't matter
And give it a background-image CSS style instead (this is due to webpack bundling and the fact I have no imports and variables in .md
files)
Problem is that the first option loads the image properly without having to specify height/width, and the 2nd approach shows nothing unless I specify height/width.
Why is this, and is there a way to bypass this without specifying height/width for every such occurence?
The best you can do is calculate the proportion of the img
and then use the value for padding
and cover
to fit that:
As an example if the image is 1:1
proportion:
.image {
background-image: url('http://i.imgur.com/3Zh2iqf.jpg');
background-repeat: no-repeat;
background-size:cover;
padding-top:100%;
}
<div>
<div class="image">
</div>
</div>
这篇关于Img src VS CSS背景图片没有内在尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!