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


当前回答

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

其他回答

我能想到的最好的解决办法是用百分比来指定你的宽度和高度。这将允许您根据显示器大小调整屏幕大小。它更响应式的布局。

举个例子。 你有

<br/>
<div> . //This you set the width percent to %100
    <div> //This you set the width percent to any amount . if you put it by 50% , it will be half
    </div>
 </div>

这是最好的选择,如果你想要一个响应式布局,我不建议浮动,在某些情况下浮动是可以使用的。但在大多数情况下,我们避免使用float,因为当你进行跨浏览器测试时,它会影响很多事情。

希望这对你有所帮助。

在Umbraco CMS中有这个问题,在这种情况下,你可以使用div的'style'属性将图像添加到div:

style="background: url('@(image.mediaItem.Image.umbracoFile)') no-repeat scroll 0 0 transparent; height: @(image.mediaItem.Image.umbracoHeight)px"

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

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

这可能会有帮助,这不是一个确切的背景,但你明白这个简单的想法吗

    <style>
div {
    float: left;
    position: relative;
}
div img {
    position: relative;
}

div div {
    position: absolute;
    top:0;
    left:0;
}
</style>

<div>
    <img src="http://www.planwallpaper.com/static/images/recycled_texture_background_by_sandeep_m-d6aeau9_PZ9chud.jpg" />
    <div>Hello</div>
</div>