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


你可以在服务器端做:通过测量图像,然后设置div大小,或者用JS加载图像,读取它的属性,然后设置div大小。

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

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

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

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

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

另一种可能效率较低的解决方案是将图像包含在设置为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>

如果你可以在Photoshop中制作一张图像,其中主图层的不透明度为1左右,基本上是透明的,将img放在div中,然后将真实的图片作为背景图像。然后设置img的不透明度为1,并添加你想要的尺寸。

这张图片就是这样做的,你甚至不能把不可见的图像拖出页面,这很酷。

添加到div

style="overflow:hidden;"

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

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

有一种非常酷的方法可以让背景图像像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/

我已经处理这个问题有一段时间了,决定写一个jquery插件来解决这个问题。 这个插件会找到所有带有“show-bg”类的元素(或者你可以传递给它你自己的选择器),并计算它们的背景图像尺寸。 您所要做的就是包含这段代码,用class="show "标记所需的元素

享受吧!

https://bitbucket.org/tomeralmog/jquery.heightfrombg

这个怎么样?

.fixed-centered-covers-entire-page { 保证金:汽车; 背景图片:url (https://i.imgur.com/Ljd0YBi.jpg); 平铺方式:不再重演;background-size:封面; 背景位置:50%; background - color: # fff; 左:0; 右:0; 上图:0; 底部:0; z - index: 1; 位置:固定; } < div class = " fixed-centered-covers-entire-page " > < / div >

演示:http://jsfiddle.net/josephmcasey/KhPaF/

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

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

我想在图像的中心有一个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>

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

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

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

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

我用jQuery解决了这个问题。直到新的CSS规则允许这种类型的行为,我发现这是最好的方法。

设置你的divs

下面是你想要显示背景的div(“hero”),然后是你想要覆盖在背景图像上方的内部内容/文本(“inner”)。你可以(也应该)将内联样式移动到英雄类中。我把它们留在这里,这样就可以快速和容易地看到应用到它的样式。

<div class="hero" style="background-image: url('your-image.png'); background-size: 100%; background-repeat: no-repeat; width: 100%;">
    <div class="inner">overlay content</div>
</div>

计算图像纵横比

接下来,通过将图像的高度除以宽度来计算图像的纵横比。例如,如果你的图像高度是660,宽度是1280,那么长宽比就是0.5156。

设置一个jQuery窗口大小调整事件来调整高度

最后,添加一个jQuery事件监听器来调整窗口大小,然后根据纵横比计算英雄div的高度并更新它。这种解决方案通常会在底部留下一个额外的像素,因为使用纵横比的计算不完美,所以我们在结果大小中添加一个-1。

$(window).on("resize", function ()
{
    var aspect_ratio = .5156; /* or whatever yours is */
    var new_hero_height = ($(window).width()*aspect_ratio) - 1;
    $(".hero").height(new_hero_height);
}

确保它在页面加载时工作

您应该在页面加载时执行上面的resize调用,以便在一开始就计算出图像的大小。如果你不这样做,那么英雄div将不会调整,直到你调整窗口的大小。我设置了一个单独的函数来进行大小调整。下面是我使用的完整代码。

function updateHeroDiv()
{
    var aspect_ratio = .5156; /* or whatever yours is */
    var new_hero_height = ($(window).width()*aspect_ratio) - 1;
    $(".hero").height(new_hero_height);
}

$(document).ready(function() 
{       
    // calls the function on page load
    updateHeroDiv(); 

    // calls the function on window resize
    $(window).on("resize", function ()
    {
        updateHeroDiv();        
    }
});

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

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

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

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

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

我有这个问题,并找到了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属性来处理屏幕大小并修复这个问题。

如果它是一个单一的预定背景图像,你想要div在不扭曲背景图像的纵横比的情况下进行响应,你可以首先计算图像的纵横比,然后创建一个div,通过以下步骤保持它的纵横比:

假设你想要一个4/1的纵横比,div的宽度是32%:

div {
  width: 32%; 
  padding-bottom: 8%; 
}

这是因为填充是根据包含元素的宽度计算的。

我能想到的最好的解决办法是用百分比来指定你的宽度和高度。这将允许您根据显示器大小调整屏幕大小。它更响应式的布局。

举个例子。 你有

<br/>
<div> . //This you set the width percent to %100
    <div> //This you set the width percent to any amount . if you put it by 50% , it will be half
    </div>
 </div>

这是最好的选择,如果你想要一个响应式布局,我不建议浮动,在某些情况下浮动是可以使用的。但在大多数情况下,我们避免使用float,因为当你进行跨浏览器测试时,它会影响很多事情。

希望这对你有所帮助。

你可以这样做

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

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

我看了一些解决方案,它们都很棒,但我觉得我找到了一个非常简单的方法。

首先,我们需要从背景图像中获取比例。我们简单地将一个维度划分为另一个维度。然后是66.4%

当我们有图像比率时,我们可以简单地计算div的高度,将比率乘以视口宽度:

height: calc(0.664 * 100vw);

对我来说,它工作,正确设置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'这样的东西。

我会做相反的事情,将图像放在主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>

这招对我很管用:

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

添加到原来接受的答案只需添加样式宽度:100%;到内部图像,以便它将自动收缩/扩展的移动设备,而不会在移动视图中采取大的顶部或底部边距。

<div style="background-image: url(http://your-image.jpg);background-position:center;background-repeat:no-repeat;background-size: contains;height: auto;"> <img src="http://your-image.jpg" style="可见性:隐藏;宽度:100%;“/> < / div >

受到最受欢迎的答案的启发,我最终想出了一个使用min-height和“vw”单位的解决方案

我得到了一个比例非常不寻常的图像

通过我最终使用的实验

    min-height: 36vw;

该值必须根据图像的比例变化

CSS代码使用在我的实际页面:

    background:url('your-background-image-adress') center center no-repeat;
    background-size: 100%;
    background-position: top center;
    margin-top: 50px;
    width: 100%;
    min-height: 36vw;

码笔示例https://codepen.io/viniciusrad/pen/GRNPXoL

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