我如何让一个div自动调整到背景的大小,我为它没有设置一个特定的高度(或最低高度)?
当前回答
我敢肯定这东西在这里永远不会被看到。但如果你的问题和我一样,这就是我的解决方案
.imaged-container{
background-image:url('<%= asset_path("landing-page.png") %> ');
background-repeat: no-repeat;
background-size: 100%;
height: 65vw;
}
我想在图像的中心有一个div,这将允许我这样做。
其他回答
事实上,当你知道怎么做的时候,这很简单:
<section data-speed='.618' data-type='background' style='background: url(someUrl)
top center no-repeat fixed; width: 100%; height: 40vw;'>
<div style='width: 100%; height: 40vw;'>
</div>
</section>
诀窍是将所附的div设置为普通div,其维度值与背景维度值相同(在本例中为100%和40vw)。
也许这有帮助,这不是一个确切的背景,但你能理解:
<style>
div {
float: left;
position: relative;
}
div img {
position: relative;
}
div div {
position: absolute;
top:0;
left:0;
}
</style>
<div>
<img src="http://antwrp.gsfc.nasa.gov/apod/image/0903/omegacen_davis.jpg" />
<div>Hi there</div>
</div>
有一种非常酷的方法可以让背景图像像img元素一样工作,这样它就可以自动调整它的高度。你需要知道图像的宽高比。将容器的高度设置为0,并根据图像比例将填充顶部设置为百分比。
它看起来如下所示:
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: contain;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 66.64%; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
你得到了一个具有自动高度的背景图像,这就像一个img元素一样。这是一个工作原型(你可以调整大小并检查div高度):http://jsfiddle.net/8m9ur5qj/
添加到原来接受的答案只需添加样式宽度:100%;到内部图像,以便它将自动收缩/扩展的移动设备,而不会在移动视图中采取大的顶部或底部边距。
<div style="background-image: url(http://your-image.jpg);background-position:center;background-repeat:no-repeat;background-size: contains;height: auto;"> <img src="http://your-image.jpg" style="可见性:隐藏;宽度:100%;“/> < / div >
另一种可能效率较低的解决方案是将图像包含在设置为visibility: hidden;的img元素下。然后使周围div的背景图像与图像相同。
这将把周围的div设置为img元素中图像的大小,但将其显示为背景。
<div style="background-image: url(http://your-image.jpg);">
<img src="http://your-image.jpg" style="visibility: hidden;" />
</div>