views:

4798

answers:

3

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?

Any help appreciated!

+1  A: 

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.

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

Itay Moav
Sounds good but I am looking for a CSS solution if possible!
JohnIdol
edited my answer, might be what you need.
Itay Moav
+1  A: 

There is no way to auto adjust for background image size using 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.

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.

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?

Orion Edwards
Thanks - but I need it as background so the image trick won't do it. i guess I am gonna hack up some javascript as you say worst case scenario but it's probably not worth it.
JohnIdol
^^ That's probably not a good idea. The browser may take several seconds before your image gets downloaded, and you can't measure it until then, so your div will be hanging out at the wrong size for quite some time!
Orion Edwards
A: 

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