根据动态高度的图像设置高度

Set the height according to the image with dynamic height

目前,我正在使用以下代码:

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

下面是该代码的样子(将浏览器 window 调整到 750 像素以下即可查看):http://mitt-galleri.nu/P1290364.

使用此解决方案,无论 window 的大小如何,DIV 的高度始终与图像一样高。我想根据图像的高度设置 DIV (不仅是图像)的高度。我已经测试 min-height: 100% 但背景颜色仍然可见。 DIV 只是在高度上比没有 min-height: 100% 时更小。

由于我使用的是 position: absolute,因此 photo-medium 下面的内容我也有 margin-top: '.$image_height.'px。我还希望它根据图像的高度具有动态高度。

我该如何解决这个问题 "problem"?

除非你真的必须,为什么要把它作为背景图片?将其添加为 img 标签,设置宽度 100%,高度自动,并且不要在父级上设置任何高度 div.