Cart Cart - 1 year ago 55
HTML Question

Setting an image as a background of <div> without pixels

I need to set an image as a background of div but i haven't founded a way how to do it without setting the exact height of div in pixels. I want the div to be always the size of the picture and when resolution is smaller to adjust the resolution. I don't want to do it by pixels and @media, there must be a simplier way.

html

<div class="foo">
</div>


css

.foo{
height: "exact height of picture of bg"; !!!
background: url("./foo/bar.jpg") 0 0 no-repeat black;
}


any ideas?

thanks

Answer Source

If you are trying to make the background image responsive when your div is resized the best way to do that is to set the background-size of the div to:

background-size:100% 100%;

That way you can still put content over the <div> background image like you are trying to do. You couldn't do that with an <img> element