使弹性项目使用父项的 100% 高度,并带有弹性方向:行



所以我试图在弹性容器内有 3 个高度和宽度相等的弹性项目。我成功地使 3 个弹性项目具有相等的宽度。但是,第一个弹性项有一个div (.images(,它也是一个弹性容器,它比其他 2 个弹性项的 (.images(div 包含更多的子项。这会导致第一个弹性项目的高度大于其他 2 个。如何使其他 2 个 flex 项目的高度与第一个项目的高度相同,即使它们没有相同数量的子项?我研究了这个问题,但只有在 flex-direction 属性设置为列时才找到答案。在我的例子中,flex-direction 属性设置为在 flex 容器内行。

body {margin: 0}
.flex-container {
display: flex;
flex-direction: row;
width: 100%;
}
.flex-items {
width: 33.333%;
height: 100%;
}
.images {
display: flex;
flex-direction: row;
flex-wrap: wrap;
height: 100%;
justify-content: center;
}
<div class="flex-container">
<div class="flex-items">
<h1>Some Title</h1>
<div class="images">
<img src="image1.jpg" alt="">
<img src="image2.jpg" alt="">
<img src="image3.jpg" alt="">
<img src="image4.jpg" alt="">
<img src="image5.jpg" alt="">
</div>
</div>
<div class="flex-items">
<h1>Some Title</h1>
<div class="images">
<img src="image6.jpg" alt="">
<img src="image7.jpg" alt="">
</div>
</div>
<div class="flex-items">
<h1>Some Title</h1>
<div class="images">
<img src="image8.jpg" alt="">
<img src="image9.jpg" alt="">
</div>
</div>
</div>

您需要为 .images 中的图像提供 100% 的高度和自动宽度 - 如果您希望它们按比例缩放,如下所示:

.images {
display: flex;
flex-direction: row;
flex-wrap: wrap;
height: 100%; (images is getting 100% height, but nothing is telling its children to go up in height)
justify-content: center;
}
.images img { (address the children)
height:100%;
width:auto;
}

如果您不设置图像的宽度和高度,他们将使用自动,并根据您使用的浏览器将其缩放到 flex 框。

图像可以内联操作,也可以通过使用 height 或 width 属性使用 css,下面是两者的示例。

内联示例 1:

<img src="#.png" width="auto" height="100%" />

CSS 示例 2:

div.images > img {  
height: 100%;  
width: auto;  
}   
优化

网页的图像也是个好主意,而不是依赖自动缩放以获得最佳效果。毕竟,您是知道最终结果应该是什么的人。

:)

最新更新