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


当前回答

这招对我很管用:

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%;

其他回答

这可能会有帮助,这不是一个确切的背景,但你明白这个简单的想法吗

    <style>
div {
    float: left;
    position: relative;
}
div img {
    position: relative;
}

div div {
    position: absolute;
    top:0;
    left:0;
}
</style>

<div>
    <img src="http://www.planwallpaper.com/static/images/recycled_texture_background_by_sandeep_m-d6aeau9_PZ9chud.jpg" />
    <div>Hello</div>
</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>

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

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

受到最受欢迎的答案的启发,我最终想出了一个使用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

添加到div

style="overflow:hidden;"