使div大小适合背景图片 [英] Fit div size to background image
问题描述
我正在尝试设置div的大小(宽度和高度)以匹配其背景图片的大小,但是我无法使其正常工作. 背景图片的大小必须以百分比为单位,因为我要处理的是自适应网站.在较小的屏幕上,背景应完整显示(宽度较小,但仍成比例),并且具有图像的div应该遵循该尺寸.
I'm trying to set the size (both width and height) of a div to match it's background image size, but I can't get it working. The background image size has to be in percentages, because I'm dealing with a responsive website. On smaller screens, the background should be displayed completely (with less width, but still proportional), and the div who has the image should follow that size.
我尝试了各种背景大小的值,例如auto 100%,cover,contain等,但没有任何效果. 这里也有类似的问题:将div缩放为背景图像大小,但是也没有解决我的问题.
I tried various values of the background-size, such as auto 100%, cover, contain, etc. but nothing did the trick. There's a similar question here about this: scale div to background image size but it didn't solve my problem either.
如果有人知道该怎么做,我将非常感激.
I'd really appreciate if someone knows how to do it.
我做了一个小提琴来展示这种行为: http://jsfiddle.net/osv1v9re/5/ 这行是使背景图片如此小的原因:
I made a fiddle to show the behavior: http://jsfiddle.net/osv1v9re/5/ This line is what is making the background image so small:
background-size: auto 100%;
但是如果将其删除,则背景将填充适当的宽度,但不会填充高度.
But if it is removed is removed, the background will fill the proper width, but not the height.
推荐答案
标记无法适应背景图片的大小,您需要使用标记并在高度之间选择:div或javascript自动
tag cannot adapt to background-image size, you need to use an tag and choose between height: auto for the div or 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;
}
这篇关于使div大小适合背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!