我如何让一个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,因为当你进行跨浏览器测试时,它会影响很多事情。
希望这对你有所帮助。
其他回答
受到最受欢迎的答案的启发,我最终想出了一个使用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
添加到原来接受的答案只需添加样式宽度: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 style="background-image: url(http://your-image.jpg); position:relative;">
<img src="http://your-image.jpg" style="opacity: 0;" />
<div style="position: absolute;top: 0;width: 100%;height: 100%;">my content goes here</div>
</div>
有一个纯CSS的解决方案,其他的答案错过了。
“content:”属性主要用于在元素中插入文本内容,但也可以用于插入图像内容。
.my-div:before {
content: url("image.png");
}
这将导致div将其高度调整为图像的实际像素大小。要调整宽度,添加:
.my-div {
display: inline-block;
}
事实上,当你知道怎么做的时候,这很简单:
<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)。