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

其他回答

没有办法使用CSS自动调整背景图像大小。

正如其他人所提到的,您可以通过测量服务器上的背景图像,然后将这些属性应用到div来解决这个问题。

你也可以修改一些javascript来根据图片大小调整div的大小(一旦图片已经下载)——这基本上是一样的事情。

如果你需要你的div自动适应图像,我可能会问你为什么不放一个<img>标签在你的div?

我有这个问题,并找到了Hasanavi的答案,但我在宽屏上显示背景图像时遇到了一个小bug -背景图像没有扩散到屏幕的整个宽度。

所以这是我的解决方案-基于Hasanavi的代码,但更好…这应该适用于超宽屏幕和手机屏幕。

/*WIDE SCREEN SUPPORT*/
@media screen and (min-width: 769px) { 
    div {
        background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
        background-size: cover;
        background-repeat: no-repeat;
        width: 100%;
        height: 0;
        padding-top: 66.64%; /* (img-height / img-width * container-width) */
                    /* (853 / 1280 * 100) */
    }
}

/*MOBILE SUPPORT*/
@media screen and (max-width: 768px) {
    div {
        background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
        background-size: contain;
        background-repeat: no-repeat;
        width: 100%;
        height: 0;
        padding-top: 66.64%; /* (img-height / img-width * container-width) */
                    /* (853 / 1280 * 100) */
    }
}

你可能已经注意到了,background-size: contains;属性不适合超宽屏幕,背景尺寸:覆盖;属性不适合移动屏幕,所以我使用这个@media属性来处理屏幕大小并修复这个问题。

添加到div

style="overflow:hidden;"

我敢肯定这东西在这里永远不会被看到。但如果你的问题和我一样,这就是我的解决方案

.imaged-container{
  background-image:url('<%= asset_path("landing-page.png") %> ');
  background-repeat: no-repeat;
  background-size: 100%;
  height: 65vw;
}

我想在图像的中心有一个div,这将允许我这样做。

假设你有这样的东西:

<div class="content">
    ... // inner HTML
</div>

你想给它添加一个背景,但你不知道图像的尺寸。

我也遇到过类似的问题,我用网格解决了它:

HTML

<div class="outer">
    <div class="content">
        ... // inner HTML
    </div>
    <img class="background" />
</div>

CSS

.outer{
    display: grid;
    grid-template: auto / auto;
    // or you can assign a name for this block
}
.content{
    grid-area: 1 / 1 / 2 / 2;
    z-index: 2;
}
.background{
    grid-area: 1 / 1 / 2 / 2;
    z-index: 1;
}

z索引是用来放置背景图像的,你当然可以放置img。div.content上面的背景。

注意:这可能会导致div.content具有与图片相同的高度,所以如果div.content有任何根据其高度放置的子元素,你可能想要设置一个数字,而不是像'auto'这样的东西。