html - 使 flexbox 行成为最短子元素的高度?

标签 html css flexbox

我在使用 Flexbox 时遇到了一些困难。目标是让行的高度与最短的子元素相同。以两张图片为例,一张高度为200px,另一张高度为120px。以下示例在 <img> 时按预期工作元素是 flex 元素的直接子元素。

.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 元素的高度扩展到最高的子元素:

.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">的解决方案是什么?最短子元素的高度?

最佳答案

正如@Michael_B 所指出的,第一个示例只是因为 align-items: stretch 才显得正确。

你不能用 flex 或纯 CSS 做到这一点。如果我们有一个可以选择最短兄弟的 CSS 选择器,那么我们就可以做到这一点——但我们没有!

您可以为父项使用固定高度:

.row {
  display: flex;
  width: 100%;
  height: 120px; /* fixed height */
  background-color: 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>

或者使用 JavaScript 为您完成逻辑:

$( document ).ready(function() {
    var min_height = -1;  
    
    $("img").each(function(  ) {
        if ($(this).height() < min_height || min_height == -1) {
            min_height = $(this).height();
        }
        $('.row').height(min_height);
    })
    
    $("img").each(function(  ) {
        $(this).height(min_height);
    });
});
.row {
  display: flex;
  width: 100%;
  background-color: orange;
  align-items: flex-start
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>

关于html - 使 flexbox 行成为最短子元素的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54317997/

相关文章:

html - 如何垂直偏移 CSS 中的元素符号或内容?

FlexBox 布局安卓。如何删除 View 之间的垂直间隙?

css - FlexBox 对齐属性的问题

javascript - Fancybox 在同一页面上使用多个画廊

php - 如何更新 HTML 中特定表格行的数据?

css - 生产中没有带导轨的图像?

html - 嵌套 Flexbox 扩展问题

javascript - 将 div 从列表移动到另一个位置

html - Bootstrap Content Spills over Width of Navbar on Mobile -- 学术 session 网站

JavaScript 函数无法加载