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


当前回答

添加到div

style="overflow:hidden;"

其他回答

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

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

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

我用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();        
    }
});

你可以这样做

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

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

有一种非常酷的方法可以让背景图像像img元素一样工作,这样它就可以自动调整它的高度。你需要知道图像的宽高比。将容器的高度设置为0,并根据图像比例将填充顶部设置为百分比。

它看起来如下所示:

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) */
}

你得到了一个具有自动高度的背景图像,这就像一个img元素一样。这是一个工作原型(你可以调整大小并检查div高度):http://jsfiddle.net/8m9ur5qj/