使 div 尺寸适合背景图片

Fit div size to background image

我正在尝试设置 div 的大小(包括宽度和高度)以匹配它的背景图像大小,但我无法让它工作。 背景图像大小必须以百分比表示,因为我正在处理一个响应式网站。在较小的屏幕上,背景应完全显示(宽度较小,但仍成比例),并且拥有图像的 div 应遵循该尺寸。

我尝试了背景大小的各种值,例如 auto 100%、cover、contain 等,但没有任何效果。 这里有一个类似的问题:scale div to background image size 但它也没有解决我的问题。

如果有人知道怎么做,我将不胜感激。

编辑: 我做了一个 fiddle 来显示行为:http://jsfiddle.net/osv1v9re/5/ 这条线使背景图像变得如此之小:

background-size: auto 100%;

但是如果删除它,背景将填充适当的宽度,而不是高度。

*{
    padding: 0;
    margin: 0;
}


div{
    width: 100%;
}
div figure{
    padding-top: 36.56%;  /* 702px/1920px = 0.3656 */
    display: block;
    background: url("https://st.fl.ru/images/landing/bg2.jpg") no-repeat center top;
    background-size: cover;  
}
<div>    
    <figure></figure>
</div>

您可以使用 padding-bottom 或 padding-top 来获得响应高度 因为您无法将“%”中的高度 属性 固定为“%”中的宽度。

div{

 background-image: url(url);
 background-repeat: no-repeat;
 background-size: 100% 100%;
 background-position: center;

 margin: 0 auto;

 width: 100%;
 padding-bottom:  heightPicure / widthPicture + %; //do it manually or using scss rules

}

标签无法适应背景图像大小,您需要使用标签并在高度之间进行选择:div 或 javascript

为自动
// **** Problem ****

// Wrong html :
<div class="my_class"><div>

// with css :
.my_class {
    width: 100%;
    height: 100%;
    background-image: url(/images/my-image.jpg);
    background-size: 100%;
    background-position: center;
    background-repeat: no-repeat;
}

//****  Solution ****

// use css:
.my_class {
    width: 100%;
    height: 100%;
    background-image: url(/images/my-image.jpg);
    background-size: contain;
}