动态加载图像并保持纵横比

问题描述 投票:1回答:1

我有一个图片库,我正在用PHP动态添加图片。一些图像是水平的,一些是垂直的。如何在不知道图像是水平还是垂直的情况下设置图像的宽度/高度并保持纵横比?现在,图像看起来正方形。理想情况下,我希望客户端无需调整代码即可更改图像。

<?php
$filelist = glob("*.JPG");
foreach ($filelist as $file) {
    echo '<div class="gallerycell">';
    echo '<a href="'.$file.'"><img src="'.$file.'" width="300" height="300"></a>';
    echo '<p>'.substr($file,strpos($file,'/') + 0,-4).'</p>';
    echo '</div>';
}
?>

.gallerycell {
    display: inline-block;
    width: 300px;
    height: 300px;
    text-align: center;
    margin: 30px;
}
php html css
1个回答
1
投票

要使图像完全响应,而不更改其宽高比,请将这些规则添加到img元素:

img {
  display: block; /* removes bottom margin/whitespace */
  width: 100%; /* also scales with 100vw */
  max-height: 100vh; /* doesn't scale with 100% */
}
© www.soinside.com 2019 - 2024. All rights reserved.