CSS: How to set container size equal to background image size

css

Solution

Instead of using a background image, you could use a `img` element and set the containing div's display to `inline-block`. You'd then need to create an inner div to wrap the content and position it absolutely relative to the containing div. Since the `img` is the only thing in the flow, the containing div will resize relative to the image.

Pretty much a hack, but I think it would give the effect you are looking for.

http://jsfiddle.net/Km3Fc/

HTML

<div class="wrap">
    <img src="yourImg.jpg" />
    <div class="content">
        <!-- Your content here -->
    </div>
</div>

CSS

.wrap {
    display: inline-block;
    position: relative;
}

.wrap img + .content {
    position: absolute;
    top: 0;
    left: 0;
}

Problem

I know how to stretch background image to fit its container (with `background-size` property). But how to achieve the other way around without setting width and height manually? To better make my point, assume we have a `p` element with one line of text and set its background-image to an picture of 800*600px. How to adjust the width and height of `p` automatically to 800*600? I ask the question because I am looking for a better workflow. It's quite annoying to change width and height in CSS every time I change the image size in Photoshop. The workflow is like below: - Change image in Photoshop (likely end up with a slightly different image dimension) - Remember that new dimension - Go into CSS file looking for that particular element which uses that image as bg - Change width and height of the element (if i still remember them correctly..)

Original source