使用flexbox创建可调整大小和可伸缩的图像网格

时间:2019-06-03 20:52:42

标签: html css flexbox

我正在尝试使用FlexBox创建可调整大小/可缩放的图像网格。

问题在于,每当由于调整窗口大小而导致图像比例过薄时,FlexBox都会在前几行中放置其他图像以填充空间。

在某些窗口比例下看起来不错。但是,如果窗口的高度太短而宽度太长,则较低行的图像将移至较高行。

我尝试使用弹性框和表格。当使用FlexBox时,我还尝试使用图像的flex属性设置flex项目的宽度。这样做的问题是图像会拉伸和变形以填充所需的空间。

以下是我正在使用的代码:

html, body { 
  height: 100%;
  width: 100%;
  margin: 0;
}

#flex-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;

  background-color: blue;
  height: 100%;
}

#flex-container>img {
  width: auto;
  height: auto;
  max-width: 25%;
  max-height: 50%;
  margin: auto;
}
<div id="flex-container">
  <img src="https://via.placeholder.com/150C/O https://placeholder.com/">
  <img src="https://via.placeholder.com/150C/O https://placeholder.com/">
  <img src="https://via.placeholder.com/150C/O https://placeholder.com/">
  <img src="https://via.placeholder.com/150C/O https://placeholder.com/">

  <img src="https://via.placeholder.com/150C/O https://placeholder.com/">
  <img src="https://via.placeholder.com/150C/O https://placeholder.com/">
  <img src="https://via.placeholder.com/150C/O https://placeholder.com/">
  <img src="https://via.placeholder.com/150C/O https://placeholder.com/">
</div>

我要使图像停留在同一行和同一列,仅根据页面的大小调整自身大小。

不需要使用FlexBox,但这似乎是完成此任务的最佳方法。

1 个答案:

答案 0 :(得分:1)

Flexbox是此布局的不错选择,但是当图像是flex项目时,会有一些棘手的副作用。为了使操作更简单,我发现将图像放入包装div中非常有帮助。

现在使用width控制每行的项目数,您可以使用媒体查询来随着屏幕变小来更改宽度,但是此时您需要重新考虑容器的100%固定高度

我已经在CSS中添加了注释以突出显示重要部分。

* {
  box-sizing: border-box; /* so borders and padding dont get in the way */
}

html,
body {
  height: 100%; /* you didint need width 100% here */
  margin: 0;
}

#flex-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  background-color: blue;
  height: 100%;
}

.img-wrap {
  width: 25%;
  height: 50%;
  display: flex; /* flexbox layout for the image wrappers, allows for... */
  align-items: center; /* ...easy centering */
  justify-content: center;
  padding: 10px; /* just some spacing so the images can breathe, remove if you want them edge to edge */
  border: 1px solid red; /* so you can easily see the bounds of the wrapper divs, remove this */
}

.img-wrap img {
  max-width: 100%; /* max dimensions on the images so they always fit */
  max-height: 100%;
  height: auto; /* maintain aspect ratio */
  width: auto;
}
<div id="flex-container">
  <div class="img-wrap"><img src="https://picsum.photos/200"></div>
  <div class="img-wrap"><img src="https://picsum.photos/300/200"></div>
  <div class="img-wrap"><img src="https://picsum.photos/400/800"></div>
  <div class="img-wrap"><img src="https://picsum.photos/500/250"></div>

  <div class="img-wrap"><img src="https://picsum.photos/450/505"></div>
  <div class="img-wrap"><img src="https://picsum.photos/350/520"></div>
  <div class="img-wrap"><img src="https://picsum.photos/250/300"></div>
  <div class="img-wrap"><img src="https://picsum.photos/550/200"></div>
</div>

相关问题