我如何让一个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>
我看了一些解决方案,它们都很棒,但我觉得我找到了一个非常简单的方法。
首先,我们需要从背景图像中获取比例。我们简单地将一个维度划分为另一个维度。然后是66.4%
当我们有图像比率时,我们可以简单地计算div的高度,将比率乘以视口宽度:
height: calc(0.664 * 100vw);
对我来说,它工作,正确设置div高度,并在窗口调整大小时更改它。
受到最受欢迎的答案的启发,我最终想出了一个使用min-height和“vw”单位的解决方案
我得到了一个比例非常不寻常的图像
通过我最终使用的实验
min-height: 36vw;
该值必须根据图像的比例变化
CSS代码使用在我的实际页面:
background:url('your-background-image-adress') center center no-repeat;
background-size: 100%;
background-position: top center;
margin-top: 50px;
width: 100%;
min-height: 36vw;
码笔示例https://codepen.io/viniciusrad/pen/GRNPXoL
我已经处理这个问题有一段时间了,决定写一个jquery插件来解决这个问题。 这个插件会找到所有带有“show-bg”类的元素(或者你可以传递给它你自己的选择器),并计算它们的背景图像尺寸。 您所要做的就是包含这段代码,用class="show "标记所需的元素
享受吧!
https://bitbucket.org/tomeralmog/jquery.heightfrombg
这个答案与其他答案相似,但对于大多数应用程序来说是最好的。你需要事先知道你通常做的图像大小。这将允许您添加叠加文本,标题等,没有负填充或绝对定位的图像。关键是设置填充%以匹配图像纵横比,如下面的例子所示。我使用了这个答案,本质上只是添加了一个图像背景。
.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>