html - 如何在方向: column的 flex 容器中垂直放置图像

标签 html css flexbox

我正在尝试将图像垂直放入具有特定高度的 flex 容器中。

flex-directioncolumn,图像包含在 flex-item 中,flex-basis: 100 %.

此外,图像的max-height100%

正如您在示例中看到的,图像不适合红色容器。

#container {
    background-color: red;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    height: 200px;
    width: 320px;
    justify-content: space-between;
}

#container > * {
  padding: 5px;
}

#img {
  flex: 0 1 100%;
  /* height: 100%; */
}
img {
  max-height: 100%;
  max-width: 100%;
}
<div id="container">
    <div id="img">
        <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=img&w=340&h=500">
    </div>
    <div>
      Something else
    </div>
</div>

根据规范,图像不应该收缩以垂直适合 flex 容器吗?

我发现的解决方法是将#imgheight设置为100%,但我感觉这不是这样的应该这样做。

作为补充说明,如果我将 flex-direction: row 设置为容器,它会水平适合图像(这是我期望的行为)。

最佳答案

您写道:

The workaround I found is to set the height of #img to 100%, but I have the sensation that it's not the way it should be done.

事实上,这应该这样做的。该规范的主要实现要求在子级上使用百分比高度时将 height 属性应用于父级。 (尽管这正在慢慢发展。请参阅下面我的第二个引用文献。)

引用文献:

关于html - 如何在方向: column的 flex 容器中垂直放置图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37004526/

相关文章:

html - Bootstrap 与网格混合以等于 .col 内行的高度

javascript - HTML 图像和其他组件根据页面宽度调整大小

javascript - 如何访问具有相同类名的元素的数据属性?

javascript - Safari overflow-x hidden 导致内部固定元素困惑

javascript - Angular : Adding custom script/css to partials via controller

javascript - 使用向上/向下箭头通过 AngularJS 聚焦和选择列表值

html - CSS - Flex 一项向左浮动

html - 如何让元素在 Flex 中堆叠?

html - 使用绝对定位内容时强制 Bootstrap div 垂直扩展

html - 仅使用 CSS 从 HTML 属性获取特定值