我如何让一个div自动调整到背景的大小,我为它没有设置一个特定的高度(或最低高度)?
当前回答
添加到原来接受的答案只需添加样式宽度: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 >
其他回答
如果它是一个单一的预定背景图像,你想要div在不扭曲背景图像的纵横比的情况下进行响应,你可以首先计算图像的纵横比,然后创建一个div,通过以下步骤保持它的纵横比:
假设你想要一个4/1的纵横比,div的宽度是32%:
div {
width: 32%;
padding-bottom: 8%;
}
这是因为填充是根据包含元素的宽度计算的。
我敢肯定这东西在这里永远不会被看到。但如果你的问题和我一样,这就是我的解决方案
.imaged-container{
background-image:url('<%= asset_path("landing-page.png") %> ');
background-repeat: no-repeat;
background-size: 100%;
height: 65vw;
}
我想在图像的中心有一个div,这将允许我这样做。
我能想到的最好的解决办法是用百分比来指定你的宽度和高度。这将允许您根据显示器大小调整屏幕大小。它更响应式的布局。
举个例子。 你有
<br/>
<div> . //This you set the width percent to %100
<div> //This you set the width percent to any amount . if you put it by 50% , it will be half
</div>
</div>
这是最好的选择,如果你想要一个响应式布局,我不建议浮动,在某些情况下浮动是可以使用的。但在大多数情况下,我们避免使用float,因为当你进行跨浏览器测试时,它会影响很多事情。
希望这对你有所帮助。
也许这有帮助,这不是一个确切的背景,但你能理解:
<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>
事实上,当你知道怎么做的时候,这很简单:
<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)。