Search code examples
htmlcssbackground-imagebackground-size

Set the height according to the image with dynamic height


At the moment, I am using the following code:

CSS

.photo-medium {
    background-attachment : scroll;
    background-color : #222222;
    background-repeat : no-repeat;
    background-position : center center;
    background-size : contain;
    border-radius : 0;
    margin : 0 0 30px -10px;
    width : 100%;
}

PHP & HTML

# VARIABLE
$photo_750 = 'images/photos/'.$photo['data_file_name'].'-750.'.$photo['data_file_type'];

# DIMENSION
list($image_width, $image_height) = getimagesize($photo_750);


# THE PHOTO
echo '<div class="photo-medium" style="background-image: url('.url($photo_750).'); height: '.$image_height.'px;"></div>';

# THE CONTENT
echo '<div style="margin-top: '.$image_height.'px;">';
    echo '...';
echo '</div>';

And here's how it looks like with that code (resize your browser window to under 750 pixels to see it): http://mitt-galleri.nu/P1290364.

With this solution, the height of the DIV are always as height as the image, no matter what the size of the window are. I want to set the height of the DIV (not only the image) according to the image's height. I have tested min-height: 100% but the background color are still visible. The DIV just getting smaller on the height than without min-height: 100%.

I also have margin-top: '.$image_height.'px on the content below photo-medium since I'm using position: absolute. I also want this to have a dynamic height, according to the image's height.

How can I fix this "problem"?


Solution

  • Unless you really have to, why put it as background image? Add it as an img tag, set width 100%, height auto, and don't set any height on the parent div.