如何让div高度自动调整到背景大小?

时间:2009-03-01 23:01:20

标签: css html background height

如何在不设置特定高度(或最小高度)的情况下让div自动调整为我为其设置的背景大小?

28 个答案:

答案 0 :(得分:485)

有一种非常好的方式可以让背景图像像img元素一样工作,因此它会自动调整height。您需要知道图片widthheight比率。将容器的height设置为0,并根据图像比率将padding-top设置为百分比。

它将如下所示:

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/TPEFn/2/

答案 1 :(得分:226)

另一种可能效率低下的解决方案是将图像包含在img元素集visibility: hidden;下。然后使周围div的background-image与图像相同。

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

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

答案 2 :(得分:34)

无法使用CSS自动调整背景图片大小。

你可以通过测量服务器上的背景图像然后将这些属性应用到div来解决它,就像其他人提到的那样。

你也可以修改一些javascript来根据图像大小调整div的大小(一旦图像被下载) - 这基本上是一样的。

如果你需要你的div来自动调整图像,我可能会问你为什么不在你的div中添加<img>标记呢?

答案 3 :(得分:19)

这个答案与其他答案类似,但对大多数应用程序来说总体上是最好的。你需要事先了解手头的图像尺寸。这将允许您添加叠加文本,标题等,没有负片填充或图像的绝对定位。它们的关键是设置填充%以匹配图像宽高比,如下例所示。我使用this answer并且基本上只添加了图像背景。

&#13;
&#13;
.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%;
}
&#13;
<div class="wrapper">
  <div class="main">
    This is where your overlay content goes, titles, text, buttons, etc.
  </div>
</div>
&#13;
&#13;
&#13;

答案 4 :(得分:13)

也许这可以提供帮助,但这不是一个背景,但你明白了这一点:

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

答案 5 :(得分:9)

很明确,这里永远不会一直看到这一点。但如果你的问题和我的问题一样,这就是我的解决方案:

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

我想在图像的中心有一个div,这样就可以了。

答案 6 :(得分:7)

我查看了一些解决方案,它们很棒,但是我认为我找到了一种出奇的简单方法。

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

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

height: calc(0.664 * 100vw);

对我来说,它可以正常工作,正确设置div高度并在调整窗口大小时对其进行更改。

答案 7 :(得分:7)

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

&#34;内容:&#34; property主要用于将文本内容插入元素,但也可用于插入图像内容。

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

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

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

答案 8 :(得分:5)

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

这是一个想法,将相同的图像放在div中作为IMG标记,但是给它可见性:隐藏+播放位置相对+给这个div图像作为背景。

答案 9 :(得分:5)

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

所以这是我的解决方案 - 基于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: contain;属性不适合超宽屏幕,background-size: cover;属性不适合移动屏幕,因此我使用了此@media属性使用屏幕大小并解决此问题。

答案 10 :(得分:3)

这个怎么样:))

.fixed-centered-covers-entire-page{
    margin:auto;
    background-image: url('https://i.imgur.com/Ljd0YBi.jpg');
    background-repeat: no-repeat;background-size:cover;
    background-position: 50%;
    background-color: #fff;
    left:0;
    right:0;
    top:0;
    bottom:0;
    z-index:-1;
    position:fixed;
}
<div class="fixed-centered-covers-entire-page"></div>

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

答案 11 :(得分:2)

如果它是单个预定的背景图像,并且您希望div能够在不扭曲背景图像宽高比的情况下进行响应,则可以先计算图像的纵横比,然后创建一个保留其纵横比的div。执行以下操作:

假设您希望宽高比为4/1,div的宽度为32%:

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

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

答案 12 :(得分:1)

受到最喜欢的答案的启发,我最终想出了一个使用 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

答案 13 :(得分:1)

假设您有这样的事情:

<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-index仅用于将图像实际放置在背景上,您当然可以将img.background放置在div.content上方。

注意:这可能会导致div.content具有图片的高度,因此,如果div.content有根据其高度放置的子代,则可能需要设置一个数字不是“自动”之类的。

答案 14 :(得分:1)

这对我有用:

app

答案 15 :(得分:1)

如果您知道生成时图像的比例,想要基于窗口高度的高度并且您没事targeting modern browsers (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/

答案 16 :(得分:1)

您可以做类似的事情

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

答案 17 :(得分:1)

这可能会有所帮助,但这不是一个背景,但你会得到一个简单的想法

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

答案 18 :(得分:0)

我能想到的最佳解决方案是以百分比形式指定宽度和高度。这样您就可以根据显示器尺寸重新调整屏幕。它更具响应性的布局......

对于一个实例。 你有

<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,因为当您进行跨浏览器测试时,它会影响很多东西。

希望这会有所帮助:)

答案 19 :(得分:0)

我一直在处理这个问题,并决定编写一个jquery插件来解决这个问题。 这个插件将找到所有带有“show-bg”类的元素(或者你可以传递它自己的选择器)并计算它们的背景图像尺寸。 您所要做的就是包含此代码,使用class =“show

标记所需的元素

享受!

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

答案 20 :(得分:0)

Umbraco CMS存在此问题,在这种情况下,您可以使用类似这样的内容将图像添加到div中,以用于div的'style'属性:

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

答案 21 :(得分:0)

我要反过来,然后将图像以100%的宽度放置在主div内,这将使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>

答案 22 :(得分:0)

background-size: contain;对我有用:

div {
  background-image: url('your-image.png');
  background-size: contain;
}

答案 23 :(得分:0)

要添加到原始接受的答案中,只需在内部图片中添加 width:100%样式,这样它对于移动设备将自动缩小,并且最终不会占据较大的顶部-移动视图的底部边距。

<div style="background-image: url(http://your-image.jpg);background-position:center;background-repeat:no-repeat;background-size: contain;height: auto;">
 <img src="http://your-image.jpg" style="visibility: hidden; width: 100%;" />
</div>

答案 24 :(得分:-1)

实际上,当你知道怎么做时,这很容易:

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

答案 25 :(得分:-2)

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

设置您的div

下面是你希望背景出现的div(“英雄”),然后是想要叠加在背景图像(“内部”)之上的内部内容/文本。您可以(并且应该)将内联样式移动到您的英雄类。我将它们留在这里,因此可以快速轻松地查看应用了哪些样式。

<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);
}

确保它适用于页面加载

您应该在页面加载时执行上面的调整大小调用,以便在开始时计算图像大小。如果不这样做,那么在调整窗口大小之前,英雄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();        
    }
});

答案 26 :(得分:-2)

如果您可以在Photoshop上制作图像,其中主图层的不透明度为1左右,并且基本上是透明的,请将该图像放入div中,然后将真实图片作为背景图像。然后将img的不透明度设置为1并添加所需的尺寸尺寸。

那张照片是这样完成的,你甚至无法将不可见的图像拖离页面,这很酷。

答案 27 :(得分:-4)

只需添加到div

style="overflow:hidden;"