如何仅使用flexbox制作响应式图像网格?

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

我正在开始我的第一个完整的网站项目,我已经学习了大约一个月的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>
html css image flexbox responsive-images
1个回答
0
投票

在您的示例中,您忘记将类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>

要实现此行为,您可以更改widthmax-width属性。 width属性强制宽度固定,而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

© www.soinside.com 2019 - 2024. All rights reserved.