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

其他回答

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

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

我想在图像的中心有一个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)。

如果你在构建时知道图像的比例,想要基于窗口高度的高度,并且你可以针对现代浏览器(IE9+),那么你可以使用视口单元:

.width-ratio-of-height {
  overflow-x: scroll;
  height: 100vh;
  width: 500vh; /* width here is 5x height */
  background-image: url("http://placehold.it/5000x1000");
  background-size: cover;
}

不完全是OP的要求,但可能很适合很多人看到这个问题,所以想在这里给出另一个选择。

小提琴:https://jsfiddle.net/6Lkzdnge/

如果它是一个单一的预定背景图像,你想要div在不扭曲背景图像的纵横比的情况下进行响应,你可以首先计算图像的纵横比,然后创建一个div,通过以下步骤保持它的纵横比:

假设你想要一个4/1的纵横比,div的宽度是32%:

div {
  width: 32%; 
  padding-bottom: 8%; 
}

这是因为填充是根据包含元素的宽度计算的。

我用jQuery解决了这个问题。直到新的CSS规则允许这种类型的行为,我发现这是最好的方法。

设置你的divs

下面是你想要显示背景的div(“hero”),然后是你想要覆盖在背景图像上方的内部内容/文本(“inner”)。你可以(也应该)将内联样式移动到英雄类中。我把它们留在这里,这样就可以快速和容易地看到应用到它的样式。

<div class="hero" style="background-image: url('your-image.png'); background-size: 100%; background-repeat: no-repeat; width: 100%;">
    <div class="inner">overlay content</div>
</div>

计算图像纵横比

接下来,通过将图像的高度除以宽度来计算图像的纵横比。例如,如果你的图像高度是660,宽度是1280,那么长宽比就是0.5156。

设置一个jQuery窗口大小调整事件来调整高度

最后,添加一个jQuery事件监听器来调整窗口大小,然后根据纵横比计算英雄div的高度并更新它。这种解决方案通常会在底部留下一个额外的像素,因为使用纵横比的计算不完美,所以我们在结果大小中添加一个-1。

$(window).on("resize", function ()
{
    var aspect_ratio = .5156; /* or whatever yours is */
    var new_hero_height = ($(window).width()*aspect_ratio) - 1;
    $(".hero").height(new_hero_height);
}

确保它在页面加载时工作

您应该在页面加载时执行上面的resize调用,以便在一开始就计算出图像的大小。如果你不这样做,那么英雄div将不会调整,直到你调整窗口的大小。我设置了一个单独的函数来进行大小调整。下面是我使用的完整代码。

function updateHeroDiv()
{
    var aspect_ratio = .5156; /* or whatever yours is */
    var new_hero_height = ($(window).width()*aspect_ratio) - 1;
    $(".hero").height(new_hero_height);
}

$(document).ready(function() 
{       
    // calls the function on page load
    updateHeroDiv(); 

    // calls the function on window resize
    $(window).on("resize", function ()
    {
        updateHeroDiv();        
    }
});