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

时间:2022-09-25 18:30:59

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自动调整为我为它设置的背景大小,而不设置特定的高度(或最小的高度)?

19 个解决方案

#1


200  

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

另一种可能效率不高的解决方案是将图像包含在设置为可见性的img元素下面:hidden;然后将周围div的背景图像与图像相同。

This will set the surrounding div to the size of the image in the img element 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>

#2


432  

There is a very nice and cool way to make a background image work like an img element so it adjust its height automatically. You need to know the image width and height ratio. Set the height of the container to 0 and set the padding-top as percentage based upon the image ratio.

有一种很酷的方法可以让背景图像像img元素一样工作,这样它就可以自动调整它的高度。你需要知道图像的宽度和高度比。将容器的高度设置为0,并根据图像的比例将划桨顶部设置为百分比。

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/

#3


28  

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自动匹配图像,我可能会问你为什么不把一个如何让div高度自动调整到背景大小?标签放在你的div中?

#4


18  

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

#5


11  

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>

#6


8  

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,这样我就可以得到它了。

#7


6  

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

#8


5  

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.

您可以在it服务器端执行:通过测量图像,然后设置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.

这里有一个想法,把同样的图像放在div中作为IMG标签,但是要让它可见:隐藏+播放位置相对+让这个div将图像作为背景。

#9


4  

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 @media attribute to play around with the screen sizes and fix this issue.

您可能已经注意到,后台大小:contains;属性doas不太适合超宽屏幕,而背景尺寸:cover;属性在移动屏幕上不太合适,所以我使用这个@media属性来处理屏幕大小并解决这个问题。

#10


3  

How about this :)

这个怎么样:)

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

Demo: http://jsfiddle.net/josephmcasey/KhPaF/

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

#11


1  

May be this can help, it's not exactly a background, but you get the simple idea

也许这能帮上忙,这不完全是背景,但你明白了吗

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

#12


1  

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.

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

#13


0  

Had this issue with the Umbraco CMS and in this scenario you can add the image to the div using something like this for the 'style' attribute of the 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"

#14


0  

I have been dealing with this issue for a while and decided to write a jquery plugin to solve this problem. This plugin will find all the elements with class "show-bg" (or you can pass it your own selector) and calculate their background image dimensions. all you have to do is include this code, mark the desired elements with class="show

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

Enjoy!

享受吧!

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

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

#15


0  

The best solution i can think of is by specifying your width and height in percent . This will allow you to rezise your screen based on your monitor size. its more of responsive layout..

我能想到的最好的解决方案是指定宽度和高度的百分比。这将允许您根据监视器大小重新调整屏幕大小。它的布局更灵活。

For an instance. you have

一个实例。你有

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

This is the best option if you would want a responsive layout, i wouldnt recommend float , in certain cases float is okay to use. but in most cases , we avoid using float as it will affect a quite of number of things when you are doing cross-browser testing.

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

Hope this helps :)

希望这有助于:)

#16


-1  

actually it's quite easy when you know how to do it:

事实上,当你知道怎么做的时候,这是很容易的:

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

the trick is just to set the enclosed div just as a normal div with dimensional values same as the background dimensional values (in this example, 100% and 40vw).

这个技巧就是将封闭的div设置为一个与背景维度值相同的普通div(在本例中为100%和40vw)。

#17


-1  

If you can make an image on Photoshop where the main layer has an opacity of 1 or so and is basically transparent, put that img in the div and then make the real picture the background image. THEN set the opacity of the img to 1 and add the size dimensions you want.

如果你可以在Photoshop中创建一个图像,主图层的不透明度是1左右,基本上是透明的,把img放到div中,然后把真实的图像变成背景图像。然后将img的不透明度设置为1,并添加所需的大小维度。

That picture is done that way, and you can't even drag the invisible image off the page which is cool.

那张图片就是这样做的,你甚至不能把看不见的图片从页面上拖下来,这很酷。

#18


-2  

I solved this using jQuery. Until new CSS rules allow for this type of behavior natively I find it is the best way to do it.

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

Setup your divs

设置你的div

Below you have your div that you want the background to appear on ("hero") and then the inner content/text you want to overlay on top of your background image ("inner"). You can (and should) move the inline styles to your hero class. I left them here so it's quick and easy to see what styles are applied to it.

下面是您希望背景出现在(“hero”)上的div,然后是您希望覆盖在背景图像(“inner”)上的内部内容/文本。您可以(也应该)将内联样式移动到hero类中。我把它们放在这里了,所以很容易看出应用了什么样式。

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

Calculate image aspect ratio

计算图像的长宽比

Next calculate your aspect ratio for your image by dividing the height of your image by the width. For example, if your image height is 660 and your width is 1280 your aspect ratio is 0.5156.

接下来,通过将图像的高度除以宽度来计算图像的纵横比。例如,如果图像高度为660,宽度为1280,则宽比为0.5156。

Setup a jQuery window resize event to adjust height

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

Finally, add a jQuery event listener for window resize and then calculate your hero div's height based off of the aspect ratio and update it. This solution typically leaves an extra pixel at the bottom due to imperfect calculations using the aspect ratio so we add a -1 to the resulting size.

最后,为窗口大小添加一个jQuery事件监听器,然后根据纵横比计算hero 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);
}

Ensure it works on page load

确保它在页面加载时工作

You should perform the resize call above when the page loads to have the image sizes calculated at the outset. If you don't, then the hero div won't adjust until you resize the window. I setup a separate function to do the resize adjustments. Here's the full code I use.

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

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

#19


-3  

just add to div

只是添加div

style="overflow:hidden;"

#1


200  

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

另一种可能效率不高的解决方案是将图像包含在设置为可见性的img元素下面:hidden;然后将周围div的背景图像与图像相同。

This will set the surrounding div to the size of the image in the img element 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>

#2


432  

There is a very nice and cool way to make a background image work like an img element so it adjust its height automatically. You need to know the image width and height ratio. Set the height of the container to 0 and set the padding-top as percentage based upon the image ratio.

有一种很酷的方法可以让背景图像像img元素一样工作,这样它就可以自动调整它的高度。你需要知道图像的宽度和高度比。将容器的高度设置为0,并根据图像的比例将划桨顶部设置为百分比。

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/

#3


28  

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自动匹配图像,我可能会问你为什么不把一个如何让div高度自动调整到背景大小?标签放在你的div中?

#4


18  

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

#5


11  

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>

#6


8  

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,这样我就可以得到它了。

#7


6  

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

#8


5  

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.

您可以在it服务器端执行:通过测量图像,然后设置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.

这里有一个想法,把同样的图像放在div中作为IMG标签,但是要让它可见:隐藏+播放位置相对+让这个div将图像作为背景。

#9


4  

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 @media attribute to play around with the screen sizes and fix this issue.

您可能已经注意到,后台大小:contains;属性doas不太适合超宽屏幕,而背景尺寸:cover;属性在移动屏幕上不太合适,所以我使用这个@media属性来处理屏幕大小并解决这个问题。

#10


3  

How about this :)

这个怎么样:)

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

Demo: http://jsfiddle.net/josephmcasey/KhPaF/

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

#11


1  

May be this can help, it's not exactly a background, but you get the simple idea

也许这能帮上忙,这不完全是背景,但你明白了吗

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

#12


1  

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.

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

#13


0  

Had this issue with the Umbraco CMS and in this scenario you can add the image to the div using something like this for the 'style' attribute of the 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"

#14


0  

I have been dealing with this issue for a while and decided to write a jquery plugin to solve this problem. This plugin will find all the elements with class "show-bg" (or you can pass it your own selector) and calculate their background image dimensions. all you have to do is include this code, mark the desired elements with class="show

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

Enjoy!

享受吧!

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

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

#15


0  

The best solution i can think of is by specifying your width and height in percent . This will allow you to rezise your screen based on your monitor size. its more of responsive layout..

我能想到的最好的解决方案是指定宽度和高度的百分比。这将允许您根据监视器大小重新调整屏幕大小。它的布局更灵活。

For an instance. you have

一个实例。你有

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

This is the best option if you would want a responsive layout, i wouldnt recommend float , in certain cases float is okay to use. but in most cases , we avoid using float as it will affect a quite of number of things when you are doing cross-browser testing.

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

Hope this helps :)

希望这有助于:)

#16


-1  

actually it's quite easy when you know how to do it:

事实上,当你知道怎么做的时候,这是很容易的:

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

the trick is just to set the enclosed div just as a normal div with dimensional values same as the background dimensional values (in this example, 100% and 40vw).

这个技巧就是将封闭的div设置为一个与背景维度值相同的普通div(在本例中为100%和40vw)。

#17


-1  

If you can make an image on Photoshop where the main layer has an opacity of 1 or so and is basically transparent, put that img in the div and then make the real picture the background image. THEN set the opacity of the img to 1 and add the size dimensions you want.

如果你可以在Photoshop中创建一个图像,主图层的不透明度是1左右,基本上是透明的,把img放到div中,然后把真实的图像变成背景图像。然后将img的不透明度设置为1,并添加所需的大小维度。

That picture is done that way, and you can't even drag the invisible image off the page which is cool.

那张图片就是这样做的,你甚至不能把看不见的图片从页面上拖下来,这很酷。

#18


-2  

I solved this using jQuery. Until new CSS rules allow for this type of behavior natively I find it is the best way to do it.

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

Setup your divs

设置你的div

Below you have your div that you want the background to appear on ("hero") and then the inner content/text you want to overlay on top of your background image ("inner"). You can (and should) move the inline styles to your hero class. I left them here so it's quick and easy to see what styles are applied to it.

下面是您希望背景出现在(“hero”)上的div,然后是您希望覆盖在背景图像(“inner”)上的内部内容/文本。您可以(也应该)将内联样式移动到hero类中。我把它们放在这里了,所以很容易看出应用了什么样式。

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

Calculate image aspect ratio

计算图像的长宽比

Next calculate your aspect ratio for your image by dividing the height of your image by the width. For example, if your image height is 660 and your width is 1280 your aspect ratio is 0.5156.

接下来,通过将图像的高度除以宽度来计算图像的纵横比。例如,如果图像高度为660,宽度为1280,则宽比为0.5156。

Setup a jQuery window resize event to adjust height

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

Finally, add a jQuery event listener for window resize and then calculate your hero div's height based off of the aspect ratio and update it. This solution typically leaves an extra pixel at the bottom due to imperfect calculations using the aspect ratio so we add a -1 to the resulting size.

最后,为窗口大小添加一个jQuery事件监听器,然后根据纵横比计算hero 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);
}

Ensure it works on page load

确保它在页面加载时工作

You should perform the resize call above when the page loads to have the image sizes calculated at the outset. If you don't, then the hero div won't adjust until you resize the window. I setup a separate function to do the resize adjustments. Here's the full code I use.

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

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

#19


-3  

just add to div

只是添加div

style="overflow:hidden;"