css - 可变宽度的图像条

标签 css responsive-design flexbox css-grid

晚上好

我正在尝试在我的网站上创建一个宽度可变(最大 1024 像素)的图像“栏”。我不想拉伸(stretch)图像,而是想保持恒定的高度,并根据网站宽度向栏中添加或删除图像。

作为起点,假设所有图像都具有相同的尺寸。

我考虑过同时使用网格和 flexbox ,但不知道从哪里开始。我进行了一些搜索,但找不到任何示例作为基础。

如果可以的话,我宁愿避免使用@media 查询。

如有任何帮助,我们将不胜感激。 enter image description here

最佳答案

在最基本的情况下,您可以像这样简单地隐藏所有未显示的图像:

.photo-bar {
  width: 100%;
  height: 100px; /* I deliberately set the size smaller than the image height to show that it works with different image sizes. If all of the images are actually the same height then you probably want it to match the image height */
  overflow: hidden;
}

.photo-bar img {
  height: 100%;
  
  /* This is to make sure you don't introduce spaces between the pictures */
  display: block;
  float: left;
}
<div class='photo-bar'>
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
</div>

您当然可以使用 flex-direction: row 来获得更好的效果,尽管这样获得所描述的行为会更加复杂(仅显示适合的图像)。如果您想要一个具有水平滚动条的画廊,这是一个更好的选择。

.photo-bar {
  display: flex;
  flex-direction: row;
  height: 100px;
  overflow: scroll;
  position: relative;
}

.photo-bar img {
  height: 100%;
}
<div class='photo-bar'>
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
  <img src='http://via.placeholder.com/160x120' />
</div>

关于css - 可变宽度的图像条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56820642/

相关文章:

html - 标记为无效属性值的最大宽度

css - 如何重置容器的高度?

css - 为什么 CSS min-width 会导致我的响应式网站在移动设备上放大?

Css column-count 应该只尊重第一个 child

html - flex 基础 : auto doesn't work in IE11

html - 如何为移动网站修复响应式网站的高度?

javascript - 使用 CSS 定位自身以外的样式

html - 如何在较小的div下居中较大的div

css - 进度圆圈 - 在圆圈的末端画一个小圆弧 + 更多

html - 使用 flexbox 对齐 div 文本