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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/600743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:23:14  来源:igfitidea点击:

How to get div height to auto-adjust to background size?

csshtmlbackgroundheight

提问by JohnIdol

How do I get a div to automatically adjust to the size of the background I set for it without setting a specific height (or min-height) for it?

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

采纳答案by Tmac

Another, perhaps inefficient, solution would be to include the image under an imgelement set to visibility: hidden;. Then make the background-imageof the surrounding div the same as the image.

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

This will set the surrounding div to the size of the image in the imgelement but display it as a background.

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

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

回答by Hasanavi

There is a very nice and cool way to make a background image work like an imgelement so it adjust its heightautomatically. You need to know the image widthand heightratio. Set the heightof the container to 0 and set the padding-topas percentage based upon the image ratio.

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

It will look like the following:

它将如下所示:

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) */
}

You just got a background image with auto height which will work just like an img element. Here is a working prototype (you can resize and check the div height): http://jsfiddle.net/TPEFn/2/

您刚刚获得了一个具有自动高度的背景图像,它就像一个 img 元素一样工作。这是一个工作原型(您可以调整大小并检查 div 高度):http: //jsfiddle.net/TPEFn/2/

回答by Orion Edwards

There is no way to auto adjust for background image size using CSS.

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

You can hack around it by measuring the background image on the server and then applying those attributes to the div, as others have mentioned.

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

You could also hack up some javascript to resize the div based on the image size (once the image has been downloaded) - this is basically the same thing.

您还可以修改一些 javascript 以根据图像大小调整 div 的大小(一旦图像已下载)-这基本上是相同的。

If you need your div to auto-fit the image, I might ask why don't you just put an <img>tag inside your div?

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

回答by horsejockey

This answer is similar to others, but is overall the best for most applications. You need to know the image size before hand which you usually do. This will let you add overlay text, titles etc. with no negative padding or absolute positioning of the image. They key is to set the padding % to match the image aspect ratio as seen in the example below. I used this answerand essentially just added an image background.

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

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

回答by Luca Matteis

Maybe this can help, it's not exactly a background, but you get the idea:

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

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

回答by Carpk

Pretty sure this will never been seen all the way down here. But if your problem was the same as mine, this was my solution:

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

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

I wanted to have a div in the center of the image, and this will allow me of that.

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

回答by Bernie Sumption

There is a pure CSS solution that the other answers have missed.

有其他答案遗漏的纯 CSS 解决方案。

The "content:" property is mostly used to insert text content into an element, but can also be used to insert image content.

"content:" 属性主要用于将文本内容插入到元素中,但也可用于插入图像内容。

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

This will cause the div to resize its height to the actual pixel size of the image. To resize the width too, add:

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

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

回答by Itay Moav -Malimovka

You can do it server side: by measuring the image and then setting the div size, OR loading the image with JS, read it's attributes and then set the DIV size.

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

And here is an idea, put the same image inside the div as an IMG tag, but give it visibility: hidden + play with position relative+ give this div the image as background.

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

回答by martin schwartz

I had this issue and found Hasanavi's answer but I got a little bug when displaying the background image on a wide screen - The background image didn't spread to the whole width of the screen.

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

So here is my solution - based on Hasanavi's code but better... and this should work on both extra-wide and mobile screens.

所以这是我的解决方案 - 基于 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) */
    }
}

As you might have noticed, the background-size: contain;property doas not fit well in extra wide screens, and the background-size: cover;property does not fit well on mobile screens so I used this @mediaattribute to play around with the screen sizes and fix this issue.

您可能已经注意到,该background-size: contain;属性不适用于超宽屏幕,并且该background-size: cover;属性不适用于移动屏幕,因此我使用此@media属性来调整屏幕尺寸并解决此问题。

回答by Headache

If it is a single predetermined background image and you want the div to to be responsive without distorting the aspect ratio of the background image you can first calculate the aspect ratio of the image and then create a div which preserves it's aspect ratio by doing the following:

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

Say you want an aspect ratio of 4/1 and the width of the div is 32%:

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

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

This results from the fact that padding is calculated based on the width of the containing element.

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