我如何让一个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>

其他回答

假设你有这样的东西:

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

最近引入的CSS纵横比属性(~2020-2021)是一个很好的方法来做到这一点,没有填充黑客,并支持所有常绿浏览器。

因为我们需要提前知道图像的纵横比,在很多情况下,你可以提前预先确定图像的尺寸比(但并不总是用户生成的内容),你可以硬编码一个单一的风格或内联css在必要的时候。

当宽度指定时,基于提供的比率(如果高度指定,则计算宽度),Aspect-ratio将计算高度。

div { 纵横比:3 / 2;/*公共比例,如800*600px图像*/ 宽度:200 px;/*计算的高度将是133.33px,这是宽度/纵横比*/ 背景:红色;/*因此任何图像出血显示*/ 背景图片:url (https://images.unsplash.com/photo - 1631163190830 - 8770 - a0ad4aa9?ixid=mnwxmja3fdb8mhxwag90by1wywdlfhx8fgvufdb8fhx8&ixlib=rb 1.2.1&auto=format&fit=crop&w=200&q=80”); } < div > < / 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>

也许这有帮助,这不是一个确切的背景,但你能理解:

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

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

<div>
    <img src="http://antwrp.gsfc.nasa.gov/apod/image/0903/omegacen_davis.jpg" />
    <div>Hi there</div>
</div>

添加到div

style="overflow:hidden;"