我如何让一个div自动调整到背景的大小,我为它没有设置一个特定的高度(或最低高度)?


当前回答

我已经处理这个问题有一段时间了,决定写一个jquery插件来解决这个问题。 这个插件会找到所有带有“show-bg”类的元素(或者你可以传递给它你自己的选择器),并计算它们的背景图像尺寸。 您所要做的就是包含这段代码,用class="show "标记所需的元素

享受吧!

https://bitbucket.org/tomeralmog/jquery.heightfrombg

其他回答

添加到div

style="overflow:hidden;"

如果你可以在Photoshop中制作一张图像,其中主图层的不透明度为1左右,基本上是透明的,将img放在div中,然后将真实的图片作为背景图像。然后设置img的不透明度为1,并添加你想要的尺寸。

这张图片就是这样做的,你甚至不能把不可见的图像拖出页面,这很酷。

我能想到的最好的解决办法是用百分比来指定你的宽度和高度。这将允许您根据显示器大小调整屏幕大小。它更响应式的布局。

举个例子。 你有

<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

这招对我很管用:

background-image: url("/assets/image_complete_path");
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover;
height: 100%;