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


当前回答

有一个纯CSS的解决方案,其他的答案错过了。

“content:”属性主要用于在元素中插入文本内容,但也可以用于插入图像内容。

.my-div:before {
    content: url("image.png");
}

这将导致div将其高度调整为图像的实际像素大小。要调整宽度,添加:

.my-div {
    display: inline-block;
}

其他回答

这招对我很管用:

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

在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大小,或者用JS加载图像,读取它的属性,然后设置div大小。

这里有一个想法,把同样的图像在div作为IMG标签,但给它可见性:隐藏+发挥位置相对+给这个div的图像作为背景。

这个答案与其他答案相似,但对于大多数应用程序来说是最好的。你需要事先知道你通常做的图像大小。这将允许您添加叠加文本,标题等,没有负填充或绝对定位的图像。关键是设置填充%以匹配图像纵横比,如下面的例子所示。我使用了这个答案,本质上只是添加了一个图像背景。

.wrapper { width: 100%; /* whatever width you want */ display: inline-block; position: relative; background-size: contain; background: url('https://upload.wikimedia.org/wikipedia/en/thumb/6/67/Wiki-llama.jpg/1600px-Wiki-llama.jpg') top center no-repeat; margin: 0 auto; } .wrapper:after { padding-top: 75%; /* this llama image is 800x600 so set the padding top % to match 600/800 = .75 */ display: block; content: ''; } .main { position: absolute; top: 0; bottom: 0; right: 0; left: 0; color: black; text-align: center; margin-top: 5%; } <div class="wrapper"> <div class="main"> This is where your overlay content goes, titles, text, buttons, etc. </div> </div>

假设你有这样的东西:

<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'这样的东西。