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


当前回答

如果你在构建时知道图像的比例,想要基于窗口高度的高度,并且你可以针对现代浏览器(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/

其他回答

这招对我很管用:

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

我已经处理这个问题有一段时间了,决定写一个jquery插件来解决这个问题。 这个插件会找到所有带有“show-bg”类的元素(或者你可以传递给它你自己的选择器),并计算它们的背景图像尺寸。 您所要做的就是包含这段代码,用class="show "标记所需的元素

享受吧!

https://bitbucket.org/tomeralmog/jquery.heightfrombg

有一种非常酷的方法可以让背景图像像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/

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

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

我想在图像的中心有一个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属性来处理屏幕大小并修复这个问题。