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

其他回答

你可以这样做

<div style="background-image: url(http://your-image.jpg); position:relative;">
 <img src="http://your-image.jpg" style="opacity: 0;" />
<div style="position: absolute;top: 0;width: 100%;height: 100%;">my content goes here</div>
</div>

这招对我很管用:

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

另一种可能效率较低的解决方案是将图像包含在设置为visibility: hidden;的img元素下。然后使周围div的背景图像与图像相同。

这将把周围的div设置为img元素中图像的大小,但将其显示为背景。

<div style="background-image: url(http://your-image.jpg);">
 <img src="http://your-image.jpg" style="visibility: hidden;" />
</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>

最近引入的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 >