【发布时间】:2019-08-06 10:12:37
【问题描述】:
我正在使用 CSS Grid 来构建图片库模式。可点击的缩略图将调用较大的“主视图”容器中的图像。问题是,无论我尝试什么,图像要么:1)溢出其容器并将缩略图库推出模式或2)充当封面大小的图像,将所有图像裁剪为相同的尺寸。
我需要发生的事情是,所有图像(纵向或横向)在出现时都包含在网格区域内,以便整个图像可用。
我是用 React 写的,所以我也想知道这方面是否存在冲突。
到目前为止,没有任何方法可以将图像包含在特色 img 窗口中。这是我尝试过的:
1.width和max-height或max-width:和height的组合
2.object-fit: contain 和object-fit: scale-down。我实际上已经尝试了许多其他版本,看看它是否有任何区别,它实际上对输出没有影响。
3. 在 div 包装器中设置<img> 标签,并将该 div 限制为网格区域容器的大小
4. 使<img> 本身成为适合网格区域的网格项目。
.grid_container--modal {
/* notice the short height is not being kept. */
height: 100px;
width: 100%;
display: grid;
grid-template-columns: repeat(6, minmax(25px,1fr));
grid-template-rows: 1fr 6fr 2fr;
grid-gap: 3px;
grid-template-areas:
"h h h h h h"
"i i i i c c"
"g g g g c c";
}
.modal-header {
grid-area: h;
background: dodgerblue;
}
.modal-feature {
/* i is for "image" */
grid-area: i;
height: 100%;
}
.modal-feature-img {
/* with explicit measures this only sort of works.*/
max-width: 100%;
}
.modal-info {
grid-area: c;
background: tomato;
}
.modal-gallery {
grid-area: g;
background: mediumseagreen;
}
.thumbnail {
max-width: 50px;
height: auto;
margin: 0 5px;
padding: 3px;
border: 1px solid #ccc;
}
<div class='grid_container--modal'>
<div class="modal-header">
<h1>header content</h1>
</div>
<!-- HERE'S WHERE THE PROBLEM LIES -->
<div class="modal-feature">
<img class='modal-feature-img' src='https://placeimg.com/640/480/any' />
</div>
<div class="modal-info">
Cras mattis consectetur purus sit amet fermentum. Aenean lacinia bibendum nulla sed consectetur. Sed posuere consectetur est at lobortis.
</div>
<div class="modal-gallery">
<img class="thumbnail" src="https://via.placeholder.com/300.png/eee/333">
</div>
</div>
截至目前,这就像封面背景或 object-fit: cover 一样工作并裁剪我的图像,但(至少)不会溢出容器并将其他东西推出。我需要它来不裁剪图像并将它们包含在网格区域内。
【问题讨论】:
-
你可以用 css 解决这个问题。但请添加minimal reproducible example。一个典型的技巧是使用 css 将图像的宽度或/和高度设置为 0,以便网格(或 flex)容器仅扩展为图像的固有大小。
-
创建一个最小的例子,去掉不相关的代码,使用编辑器的“sn-p”特性。这是一个 css 问题,所以不需要 jsx/react 代码。只需在 sn-p 中使用 html。
-
Haken,因为我需要网格中的内容来显示问题,所以我真的试图将其缩小到基本要素。我尝试将宽度/高度/两者都设置为 0,但这并没有影响我的输出。但是,我已将其放入 sn-p 中,并删除了所有 JSX。