css - flex 元素中的自动调整图像大小

标签 css flexbox

我有以下 html:

<div class="main-container">
    <h1>A title</h1>
    <p>Some text</p>
    <div class="sub-container">
        <img src="">
    </div>
</div>

使用以下 CSS:

.main-container{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}
.sub-container{
    flex-grow:2;
    background-color: green;
}

请注意,我不知道“main-container”上方容器的大小。我正在使用 flex,因为我希望“主容器”中的 div 占据底部的所有剩余空间。

我想要的是在“子容器”中有一个图像,它在两个方向(高度和宽度)都适合其父级的大小。现在,如果我将图像添加到“子容器”中,它会溢出并且根本不会缩放。 我知道 flex 仅适用于直接子级(即“子容器”而不是内部图像)。我也尝试在“子容器”上使用 flex,但我无法取得令人满意的结果。

最佳答案

这是您想要的布局吗?

使用flex: 1 1 0 来控制子容器,使用width: 100% 可以使图像适合容器。

.main-container{
  border: 3px solid green;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}
.sub-container{
    flex-grow: 1 1 0;
    background-color: green;
    display: flex;
}

.sub-container img {
   width: 100%;
   height: 100%;
}
<div class="main-container">
    <h1>A title</h1>
    <p>Some text</p>
    <div class="sub-container">
        <img src="https://picsum.photos/1080/600">
    </div>
</div>

关于css - flex 元素中的自动调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40279896/

相关文章:

css - 无法让背景图像显示 - 不是路径问题

html - 如何修复 Webkit 浏览器的这种奇怪的盒模型行为?

jquery - 根据滚动位置更改 div 颜色

html - 使用 CSS 将 HTML 导出为 PDF 脚本

html - CSS div 内容和字体图标缩放

html - 柔性 : how to align the content of 2 rows to each other (same width)

css - 包装元素之间的 Flex Row 空间

html - Flexbox:如何让一个元素粘在容器的右端?

html - 力求垂直对齐元素框的边框?

html - 间隔 flex 元素的最佳方式