【问题标题】:CSS image grid without using object-fit: cover不使用 object-fit: 覆盖的 CSS 图像网格
【发布时间】:2021-03-20 22:02:28
【问题描述】:

基本上试图实现 Adob​​e Stock 和 Shutterstock 所拥有的水平砖石网格,而无需通过对象适合或任何其他拉伸来更改图像纵横比。

每个解决方案都使用 object-fit:cover,这意味着图像被裁剪。

我的图片来自不同尺寸的 API。

我最接近的是:

HTML:

<div id='container'>
    <div class='image'>
        <img src='' alt=''>
    </div>

    <div class='image'>
        <img src='' alt=''>
    </div>

    <div class='image'>
        <img src='' alt=''>
    </div>
</div

CSS:

#container {
    display: flex;
    flex-wrap: wrap;
}

.image {
    flex-grow: 1;
    margin: 2px;
    max-height: 300px;
}

img {
    max-height: 300px;
    max-width: 100%;
    min-width: 100%;
    vertical-align: bottom;
}

但这会给图像带来一些轻微的拉伸。

我们的想法是让该行占据任意数量的垂直空间,以使图像适合该行,同时保持它们各自的纵横比。

【问题讨论】:

  • 您的意思是您希望该行占用任意数量的垂直空间,还是您的代码中已有的最大高度是您所需要的?
  • 我认为最好的解决方案是任意数量的垂直空间达到限制。但我认为,如果特定图像需要大量垂直空间以确保其他所有内容对齐,则不能有限制。

标签: html css image grid responsive


【解决方案1】:

我认为 object-fit contains 在这里可能会有所帮助。但是,究竟是在所有图像高度相同的情况下看起来“最佳”,还是例如达到最大高度,这取决于最终想要的效果。

这是一个 sn-p,其中每个 img 都被赋予了一个最大高度(选择 300px 仅仅是因为这在问题的代码中,当然可以说是 30vh 或...)。也可以为每个 img 设置 300px 的高度,让它们对齐。

#container {
    display: flex;
    flex-wrap: wrap;
}

.image {
    flex-grow: 1;
    margin: 2px;
    height: 300px;
    width: auto;
    max-width: 100%;
}

img {
    max-height: 300px;
    max-width: 100%;
    min-width: 100%;
    object-fit: contain;
}
<div id='container'>
    <div class='image'>
        <img src='https://via.placeholder.com/300x300.jpg' alt=''>
    </div>

    <div class='image'>
        <img src='https://via.placeholder.com/400x200.jpg' alt=''>
    </div>

    <div class='image'>
        <img src='https://via.placeholder.com/200x400.jpg' alt=''>
    </div>
    <div class='image'>
        <img src='https://via.placeholder.com/600x300.jpg' alt=''>
    </div>
    <div class='image'>
        <img src='https://via.placeholder.com/1024x768.jpg' alt=''>
    </div>
    <div class='image'>
        <img src='https://via.placeholder.com/150x150.jpg' alt=''>
    </div>
</div>

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 1970-01-01
    • 2021-06-07
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2017-01-06
    • 1970-01-01
    相关资源
    最近更新 更多