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


当前回答

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

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

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

其他回答

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

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

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

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

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

我会做相反的事情,将图像放在主div中,宽度为100%,这将使div和图像都响应屏幕大小,

然后在主div的宽度和高度为100%的绝对定位div中添加内容。

<div class="main" style="position: relative; width: 100%;">
    <img src="your_image.png" style="width: 100%;">
    <div style="position: absolute; width: 100%; height: 100%; display: flex...">
            YOUR CONTENT
    </div>
</div>