我如何让一个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>
其他回答
我会做相反的事情,将图像放在主div中,宽度为100%,这将使div和图像都响应屏幕大小,
然后在主div的宽度和高度为100%的绝对定位div中添加内容。
<div class="main" style="position: relative; width: 100%;">
<img src="your_image.png" style="width: 100%;">
<div style="position: absolute; width: 100%; height: 100%; display: flex...">
YOUR CONTENT
</div>
</div>
也许这有帮助,这不是一个确切的背景,但你能理解:
<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>
这个答案与其他答案相似,但对于大多数应用程序来说是最好的。你需要事先知道你通常做的图像大小。这将允许您添加叠加文本,标题等,没有负填充或绝对定位的图像。关键是设置填充%以匹配图像纵横比,如下面的例子所示。我使用了这个答案,本质上只是添加了一个图像背景。
.wrapper { width: 100%; /* whatever width you want */ display: inline-block; position: relative; background-size: contain; background: url('https://upload.wikimedia.org/wikipedia/en/thumb/6/67/Wiki-llama.jpg/1600px-Wiki-llama.jpg') top center no-repeat; margin: 0 auto; } .wrapper:after { padding-top: 75%; /* this llama image is 800x600 so set the padding top % to match 600/800 = .75 */ display: block; content: ''; } .main { position: absolute; top: 0; bottom: 0; right: 0; left: 0; color: black; text-align: center; margin-top: 5%; } <div class="wrapper"> <div class="main"> This is where your overlay content goes, titles, text, buttons, etc. </div> </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>
我已经处理这个问题有一段时间了,决定写一个jquery插件来解决这个问题。 这个插件会找到所有带有“show-bg”类的元素(或者你可以传递给它你自己的选择器),并计算它们的背景图像尺寸。 您所要做的就是包含这段代码,用class="show "标记所需的元素
享受吧!
https://bitbucket.org/tomeralmog/jquery.heightfrombg