【问题标题】:How to get div height to auto-adjust to background size?如何让 div 高度自动调整为背景大小?
【发布时间】:2010-10-10 16:29:57
【问题描述】:

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

【问题讨论】:

标签: css html background height


【解决方案1】:

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

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

【讨论】:

  • 大声笑为什么需要服务器端?应该可以用 CSS 实现。
  • @GTHell haha​​ha - 检查我回答的年份
  • @ItayMoav-Malimovka 呵呵,没注意到。
【解决方案2】:

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

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

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

如果你需要你的 div 来自动适应图像,我可能会问你为什么不在你的 div 里面放一个<img> 标签?

【讨论】:

  • 谢谢 - 但我需要它作为背景,所以图像技巧不会这样做。我想我会像你说的最坏的情况那样破解一些javascript,但这可能不值得。
  • ^^ 这可能不是一个好主意。浏览器可能需要几秒钟的时间才能下载您的图片,并且在此之前您无法对其进行测量,因此您的 div 将在很长一段时间内以错误的尺寸挂起!
  • 他可以在文档准备好后运行 JavaScript。
  • 您无法使用媒体查询更改imgsrc,但您可以使用媒体查询更改用作背景图像的文件。
【解决方案3】:

也许这会有所帮助,它不完全是背景,但你明白了:

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

【讨论】:

  • 请解释为什么您将 img 的位置保持为相对位置?
  • 可能是因为float: left;打破了他的定位
【解决方案4】:

另一个可能效率低下的解决方案是将图像包含在设置为visibility: hidden;img 元素下。然后让周围div的background-image和图片一样。

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

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

【讨论】:

  • 不太有用,因为图像将使用“空间”,并且内容看起来像顶部有很大的边距。
  • 也许我遗漏了一些东西,但是如果你无论如何都要把img 放入你的标记中,为什么不干脆隐藏实际的&lt;img&gt; 和也不打扰background-image?这样做有什么好处?
  • 很好的答案,但是浏览器不是必须加载两次吗?
  • @www139 当你说加载时,你的意思是什么?图像下载后,可能会被缓存。从那时起,任何其他请求都基于本地副本。所以不行。它不会被下载两次。但是,它被加载了两次。
  • @MarkAmery background-image 最酷的事情之一是它可以使用CSS blend-modes,而img 不能。
【解决方案5】:

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

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

【讨论】:

    【解决方案6】:

    只需添加到div

    style="overflow:hidden;"
    

    【讨论】:

      【解决方案7】:

      Umbraco CMS 遇到了这个问题,在这种情况下,您可以将图像添加到 div 中,对 div 的 'style' 属性使用类似这样的东西:

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

      【讨论】:

        【解决方案8】:

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

        【讨论】:

        • 确实很棒!只是为了后代观看这个答案,如果您使用的是指南针(scss),我使用他们的辅助函数创建了一个 mixin 来为您进行计算:@mixin div-same-size-as-background-img($url) { background-image: url($url); background-size: contain; background-repeat: no-repeat; width: 100%; height: 0; padding-top: percentage(image-height($url) / image-width($url)); }
        • 仅供那些想知道的人参考,padding-top 不会创建空白,因为它只是增加了元素的高度。该图像是背景图像,因此以适当的位置和间距显示。我们必须为 CSS 想出这样的技巧是非常愚蠢的。
        • 不幸的是,padding-top 不允许您在 div 中放置任何其他内容,例如背景上的表单元素。
        • @GaryHayes 您可以将position:relative 设置为 div,并使用position:absolute; top:0; bottom:0; left:0; right:0;set 将另一个 div 放入其中
        • 虽然此方法适用于显示背景图像,但它确实会通过填充 div 来降低 div 本身的用处。 Kryptik 建议在容器内添加一个绝对定位的 div,但是为什么还要使用背景图像呢?如果您只想将所有内容置于绝对位置,则可以在内容 div 中使用实际图像。这首先违背了使用背景图像的目的。
        【解决方案9】:

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

        标记所需的元素

        享受吧!

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

        【讨论】:

          【解决方案10】:

          这个怎么样:)

          .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;
          }
          &lt;div class="fixed-centered-covers-entire-page"&gt;&lt;/div&gt;

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

          【讨论】:

            【解决方案11】:

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

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

            我想在图像的中心有一个 div,这将允许我这样做。

            【讨论】:

              【解决方案12】:

              此答案与其他答案相似,但总体上对大多数应用程序来说是最好的。您需要事先知道图像大小,这与您通常做的一样。这将允许您添加覆盖文本、标题等,而无需图像的负填充或绝对定位。他们的关键是设置填充百分比以匹配图像纵横比,如下例所示。我使用了this answer,基本上只是添加了一个图像背景。

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

              【讨论】:

              • -1 用于使用 !important - 并链接到另一个答案。请考虑从另一个答案中复制相关代码(带有归属)i,以便这个更完整,并防止链接失效。
              • @jammypeach 这个更好吗?
              • @horsejockey 除非我遗漏了一些不能缩放图像的东西。它只是掩盖它。
              • @dwkns 奇怪的是,所有后台调用都需要在一个元素中。当我在特定 id 上指定“背景:url()”和在通用类中指定“背景大小:包含”时,我发现它正在裁剪。
              • @dwkns 更新:我能够通过使用“background-image: url()”而不是“background: url()”来解决这个问题。
              【解决方案13】:

              其实只要你知道怎么做就很容易了:

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

              【讨论】:

              • 您将高度设置为窗口宽度的比例。这并非在所有情况下都有效 - 您的某些内容(例如数据速度)与您的答案无关。
              • 大多数事情“当你知道怎么做时不是很容易”吗?
              【解决方案14】:

              这可能会有所帮助,它不完全是背景,但你明白了这个简单的想法

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

              【讨论】:

                【解决方案15】:

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

                设置您的 div

                下面是您希望背景出现的 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);
                }
                

                确保它适用于页面加载

                您应该在页面加载时执行上述调整大小调用,以便在一开始就计算出图像大小。如果你不这样做,那么在你调整窗口大小之前,英雄 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! aspect-ratio
                • @mix3d 不错!这个答案来自很久以前,我知道随着时间的推移会有所改进。
                • 终于,5年后
                • 我试着简单地回复“哈!”除了评论需要 15 个字符——因此是整个句子。
                【解决方案16】:

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

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

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

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

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

                【讨论】:

                • 我喜欢这个解决方案,但是当浏览器变小时,在设置为响应式的标题图像下方会留下很多空白。
                • 这是一个简单的答案❤
                【解决方案17】:

                我遇到了这个问题并找到了 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 属性来玩转屏幕大小并解决此问题。

                【讨论】:

                  【解决方案18】:

                  如果它是单个预定的背景图像,并且您希望 div 响应而不扭曲背景图像的纵横比,您可以首先计算图像的纵横比,然后创建一个 div 保留它的纵横比执行以下操作:

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

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

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

                  【讨论】:

                    【解决方案19】:

                    我能想到的最佳解决方案是以百分比指定宽度和高度。这将允许您根据显示器尺寸调整屏幕大小。它更多的是响应式布局..

                    举个例子。 你有

                    <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 ,在某些情况下可以使用 float。但在大多数情况下,我们会避免使用 float,因为它会在您进行跨浏览器测试时影响很多事情。

                    希望这会有所帮助:)

                    【讨论】:

                      【解决方案20】:

                      你可以这样做

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

                      【讨论】:

                        【解决方案21】:

                        如果您在构建时知道图像的比例,想要基于窗口高度的高度并且您可以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/

                        【讨论】:

                          【解决方案22】:

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

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

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

                          height: calc(0.664 * 100vw);
                          

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

                          【讨论】:

                          • 是的,这是一个巧妙的技巧,但如果图像尺寸已知,为什么不简单地使用图像的高度呢?我认为我们正在寻找的是一种适用于任何图像的解决方案,无需硬编码数字......
                          • 而且基于屏幕尺寸的高度增长和缩小也不总是可取的
                          • 很好的解决方案:它可以响应浏览器的大小,并且您仍然可以使用弹性框显示。我现在就试试这个,看看我能不能完成我的工作。干杯!
                          • 但是,我很想知道为什么将图像比例乘以 100vw 可以使它起作用。干杯!
                          【解决方案23】:

                          假设你有这样的事情:

                          <div class="content">
                              ... // inner HTML
                          </div>
                          

                          你想给它添加背景,但你不知道图像的尺寸。

                          我也遇到过类似的问题,我用grid解决了:

                          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 有任何根据其高度放置的孩子,您可能需要设置一个数字而不是类似'自动'。

                          【讨论】:

                            【解决方案24】:

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

                            【讨论】:

                              【解决方案25】:

                              这对我有用:

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

                              【讨论】:

                              • 这可以缩短为background: url("/assets/image_complete_path") no-repeat center / cover; height: 100%;
                              【解决方案26】:

                              添加到原始接受的答案只需将样式 width:100%; 添加到 inner image 以便它会针对移动设备自动缩小/展开并且不会结束在移动视图中获取较大的顶部或底部边距。

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

                              【讨论】:

                                【解决方案27】:

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

                                【讨论】:

                                  【解决方案28】:

                                  recently introduced CSS aspect-ratio attribute (~2020-2021) 是一种无需填充黑客的好方法,并且在所有常青浏览器上都受支持。

                                  由于我们需要提前知道图像的纵横比,并且在许多用例中,您可以提前预先确定图像的尺寸比(但并非总是针对用户生成的内容),您可以硬编码单个样式或在必要时内联 css。

                                  aspect-ratio 将在指定宽度时根据提供的比率计算高度(如果指定高度,则计算宽度)。

                                  div {
                                      aspect-ratio: 3 / 2; /*common ratio, like an 800*600px image */
                                  
                                      width: 200px; /* computed height will be 133.33px, which is width/aspect-ratio */
                                      background: red; /* so any image bleed is shown*/
                                      background-image: url('https://images.unsplash.com/photo-1631163190830-8770a0ad4aa9?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=200&q=80');
                                  }
                                  &lt;div&gt;&lt;/div&gt;

                                  【讨论】:

                                  • 感谢您在此处留下此评论。
                                  猜你喜欢
                                  • 2012-04-10
                                  • 2019-11-29
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多