我如何让一个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)。

其他回答

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

另一种可能效率较低的解决方案是将图像包含在设置为visibility: hidden;的img元素下。然后使周围div的背景图像与图像相同。

这将把周围的div设置为img元素中图像的大小,但将其显示为背景。

<div style="background-image: url(http://your-image.jpg);">
 <img src="http://your-image.jpg" style="visibility: hidden;" />
</div>

我看了一些解决方案,它们都很棒,但我觉得我找到了一个非常简单的方法。

首先,我们需要从背景图像中获取比例。我们简单地将一个维度划分为另一个维度。然后是66.4%

当我们有图像比率时,我们可以简单地计算div的高度,将比率乘以视口宽度:

height: calc(0.664 * 100vw);

对我来说,它工作,正确设置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%;

事实上,当你知道怎么做的时候,这很简单:

<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)。