问题描述
我在使用Flexbox时遇到了一些困难.目的是使行与最短的子元素具有相同的高度.以两个图像为例,一个图像的高度为200px,另一个图像的高度为120px.当< img>
元素是flex元素的直接子代时,下面的示例可以正常工作.
I am having some difficulty using Flexbox. The goal is to have a row that is the same height as the shortest child element. Take two images as examples, one has 200px height the other has 120px height. This example below works as intended when <img>
elements are the direct children of the flex element.
.row {
display: flex;
width: 100%;
background: orange;
}
<div class="row">
<img src="https://s3.amazonaws.com/imagetest.com/purple_200.jpg" />
<img src="https://s3.amazonaws.com/imagetest.com/teal_120.jpg" />
</div>
但是,在以下示例中,flexbox元素的高度扩展为最高的子元素:
However, in the following example, the height of the flexbox element expands to the tallest child element:
.row {
display: flex;
width: 100%;
background: orange;
}
<div class="row">
<div class="col">
<img src="https://s3.amazonaws.com/imagetest.com/purple_200.jpg" />
</div>
<div class="col">
<img src="https://s3.amazonaws.com/imagetest.com/teal_120.jpg" />
</div>
</div>
使< div class ="row">
的最短子元素的高度是什么解决方案?
What is a solution to make <div class="row">
the height of the shortest child element?
推荐答案
flexbox无法自动执行此操作.
This is not something flexbox can do automatically.
您需要找到一种方法来告诉容器最矮的孩子的身高是多少,以便它可以调整其高度以匹配.JavaScript似乎是要走的路.
You'll need to find a way to tell the container what the height is of the shortest child so it can adjust its height to match. JavaScript seems the way to go.
下面的示例按预期工作..." 我想您是说行的高度是较短图像的高度(120像素).
"The example below works as intended..." I presume you mean the height of the row is the height of the shorter image (120px).
实际上,该行的高度为200px:
In fact, the row is 200px tall:
较短的图像实际上是从120像素拉伸到200像素,因为伸缩容器上的默认设置为 align-items:Stretch
,这意味着伸缩项目将扩展横轴的整个长度.(这是flexbox如何提供具有相等高度的列的布局.)
The shorter image is actually stretching from 120px to 200px because a default setting on a flex container is align-items: stretch
, meaning that flex items will expand the full length of the cross-axis. (This is how flexbox can deliver a layout with equal height columns.)
如果您使用 align-items:flex-start
覆盖默认值,则会清楚地看到较高的项目会设置容器的高度.
If you override the default with, let's say, align-items: flex-start
, you'll see clearly that the taller items sets the height of the container.
.row {
display: flex;
align-items: flex-start; /* new */
background: orange;
}
<div class="row">
<img src="https://s3.amazonaws.com/imagetest.com/purple_200.jpg" />
<img src="https://s3.amazonaws.com/imagetest.com/teal_120.jpg" />
</div>
这篇关于将flexbox行设置为最短子元素的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!