【问题标题】:Set the height according to the image with dynamic height根据具有动态高度的图像设置高度
【发布时间】:2015-02-09 13:23:32
【问题描述】:

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

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

以下是该代码的外观(将浏览器窗口大小调整到 750 像素以下即可查看):http://mitt-galleri.nu/P1290364

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

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

我该如何解决这个“问题”?

【问题讨论】:

  • 您是否尝试将高度设置为auto
  • 没有,但现在我有了。图像完全消失了。

标签: html css background-image background-size


【解决方案1】:

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

【讨论】:

  • 这是一个解决方案,是的,但我更喜欢使用background-image 更多。但是,如果我无法在您的聪明才智的帮助下解决这个“问题”,我可以使用您的解决方案
  • 没有办法根据它的背景图像大小自动调整 div,除非你想向它添加一堆 javascript 逻辑,并且任何后端解决方案都只能在加载时工作,而不是在调整大小时.
  • 好的。然后我将使用您的解决方案。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 2011-09-27
  • 2017-12-17
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
相关资源
最近更新 更多