【问题标题】:How can I make a responsive image grid using only flexbox?如何仅使用 flexbox 制作响应式图像网格?
【发布时间】:2019-09-19 12:07:57
【问题描述】:

我开始了我的第一个完整的网站项目,我已经学习 HTML 和 CSS 大约一个月了,我刚刚学习完 flexbox 的基础知识。我想知道是否可以创建一个图像网格,其中图像会自动调整大小,因为仅使用 flexbox 调整浏览器窗口的大小,这就是我现在所知道的。

我要重建的是this。左侧是一张大图像,右侧是两张较小的图像堆叠在一起。当我缩小浏览器时,图像会自动调整大小。如果您想现场查看,这里是website。只需向下滚动一点,直到你看到它。

这是我对jsfiddle 的糟糕尝试。出于某种原因,jsfiddle 没有以它们在我的计算机上显示的方式显示它。我计算机上的图像是并排的,就像我想要的那样,但是如果我稍微调整窗口大小,它就会中断到下一行。

对于那些不想处理 jsfiddle 的人,这里是相关的 HTML 和 CSS。我知道这是一团糟。

HTML:

/* Section: Gallery */

#gallery {
  display: flex;
  flex-wrap: wrap;
  background: rgb(252, 246, 237);
  text-align: center;
}

.coffee-img-1 {
  width: 500px;
  padding: 1.5rem;
  margin-right: 5rem;
  margin-top: 2rem;
  max-width: 100%;
  height: auto;
}

.coffee-img-2,
.coffee-img-3 {
  width: 400px;
  padding: 30px;
  max-width: 100%;
  height: auto;
}

.column {
  flex: 50%;
  padding: 1.5rem;
}

#gallery img:hover {
  animation-name: opacity-hover;
  animation-duration: 300ms;
  animation-fill-mode: forwards;
}

@keyframes opacity-hover {
  100% {
    opacity: 0.9;
  }
}
<!-- Gallery -->
<section id="gallery">
  <div>
    <img class="coffee-img-1" src="https://i.imgur.com/58DZwQ2.jpg" alt="Table with coffee and pastries">
  </div>
  <div class="column">
    <img class="coffee-img-2" src="https://i.imgur.com/hsSn85u.jpg" alt="Barista pulling two espresso shots">
    <img class="coffee-img-3" src="https://i.imgur.com/nmAId6V.jpg" alt="Barista brewing coffee with aeropress">
  </div>
</section>

【问题讨论】:

  • 您需要将宽度和最大宽度重新考虑为宽度和最小宽度,还有边距/填充 jsfiddle.net/xnh9tqko 以便在并排或上下对齐时对齐。当比例不够连贯以适应视觉效果时,object-fit 可能有助于最终确定和裁剪图像:)
  • @G-Cyr 我没想过这样使用 min-width 。感谢您的提示,现在看起来好多了。

标签: html css image flexbox responsive-images


【解决方案1】:

在您的示例中,您忘记将类 column 添加到第一个 div 中。像这样:

<!-- Gallery -->
<section id="gallery">
  <div class="column">
    <img class="coffee-img-1" src="https://i.imgur.com/58DZwQ2.jpg" alt="Table with coffee and pastries">
  </div>
  <div class="column">
    <img class="coffee-img-2" src="https://i.imgur.com/hsSn85u.jpg" alt="Barista pulling two espresso shots">
    <img class="coffee-img-3" src="https://i.imgur.com/nmAId6V.jpg" alt="Barista brewing coffee with aeropress">
  </div>
</section>

要实现此行为,您可以将width 属性更改为max-widthwidth 属性强制固定宽度,而 max-width(和 min-width)表示“嘿,即使我的图像大于将其调整为最大宽度 x

例子:

https://codepen.io/icaromh/pen/jRopmp

文档:

https://developer.mozilla.org/en-US/docs/Web/CSS/max-width

https://developer.mozilla.org/en-US/docs/Web/CSS/min-width

【讨论】:

  • 我知道最大宽度的东西,但我从来没有想过将列类添加到另一个 div。这立即解决了我的问题,这很有意义。这些图像正在调整自己的大小,就像我想要的那样,没有任何问题。谢谢!
猜你喜欢
  • 2016-08-25
  • 2022-01-22
  • 2016-07-11
  • 2021-08-23
  • 2014-07-14
  • 2020-07-25
  • 2013-04-25
  • 2020-03-26
  • 1970-01-01
相关资源
最近更新 更多