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


当前回答

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

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

其他回答

没有办法使用CSS自动调整背景图像大小。

正如其他人所提到的,您可以通过测量服务器上的背景图像,然后将这些属性应用到div来解决这个问题。

你也可以修改一些javascript来根据图片大小调整div的大小(一旦图片已经下载)——这基本上是一样的事情。

如果你需要你的div自动适应图像,我可能会问你为什么不放一个<img>标签在你的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 >

事实上,当你知道怎么做的时候,这很简单:

<section data-speed='.618' data-type='background' style='background: url(someUrl) 
top center no-repeat fixed;  width: 100%; height: 40vw;'>
<div style='width: 100%; height: 40vw;'>
</div>
</section>

诀窍是将所附的div设置为普通div,其维度值与背景维度值相同(在本例中为100%和40vw)。

我有这个问题,并找到了Hasanavi的答案,但我在宽屏上显示背景图像时遇到了一个小bug -背景图像没有扩散到屏幕的整个宽度。

所以这是我的解决方案-基于Hasanavi的代码,但更好…这应该适用于超宽屏幕和手机屏幕。

/*WIDE SCREEN SUPPORT*/
@media screen and (min-width: 769px) { 
    div {
        background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
        background-size: cover;
        background-repeat: no-repeat;
        width: 100%;
        height: 0;
        padding-top: 66.64%; /* (img-height / img-width * container-width) */
                    /* (853 / 1280 * 100) */
    }
}

/*MOBILE SUPPORT*/
@media screen and (max-width: 768px) {
    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) */
    }
}

你可能已经注意到了,background-size: contains;属性不适合超宽屏幕,背景尺寸:覆盖;属性不适合移动屏幕,所以我使用这个@media属性来处理屏幕大小并修复这个问题。

这招对我很管用:

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