我正在尝试使用 FlexBox 制作可调整大小/可缩放的图像网格。
问题是,每当由于调整窗口大小而导致图像比例太细时,FlexBox 就会在前面的行上放置额外的图像来填充空间。
在某些窗口比例下看起来不错。但是,如果窗口的高度太短而宽度太长,则下排的图像将移至上排。
我尝试过使用 flex 盒和表格。使用 FlexBox 时,我还尝试使用图像的 flex 属性来设置 Flex 元素的宽度。这样做的问题是图像会拉伸(stretch)和扭曲以填充所需的空间。
这是我正在使用的代码:
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,但这似乎是完成此任务的最佳方式。
最佳答案
Flexbox 是这种布局的不错选择,但当图像是 Flex 元素时,会出现一些棘手的副作用。为了使这更简单,我发现将图像放入包装 div 中非常有帮助。
现在使用宽度
控制每行的元素数,当屏幕变小时,您可以使用媒体查询来更改宽度,但您需要重新考虑容器的 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>
关于html - 使用 Flexbox 创建可调整大小且可扩展的图像网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56434407/