html - 如何使图像在 flex 容器中占据最大空间?

标签 html css image flexbox

我需要使图像在 flex 容器中采用最大尺寸(采用最大宽度或最大高度)。

由于父容器没有固定的宽度和高度,因此我无法使用 max-widthmax-height 以及 flex:1 也不起作用。

以下是问题的示例:https://jsfiddle.net/vb26u0e5/2/

我希望图像自动拍摄所有可用的绿色空间(删除 width: 40px; 第 20 行)。

#mainContainer {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  color: white;
}

#imageContainer {
  flex: 1;
  display: flex;
  justify-content: space-between;
  background-color: green;
}

#image {
  width: 40px;
}

#previous,
#next {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 25px;
  padding: 0 10px;
  background-color: purple;
}

#title,
#footer {
  text-align: center;
}

#title {
  background-color: blue;
}

#footer {
  background-color: red;
}
<div id="mainContainer">
  <div id="title">TITLE</div>
  <div id="imageContainer">
    <div id="previous">&lt;</div>
    <img id="image" src="https://via.placeholder.com/1920x1080" />
    <div id="next">&gt;</div>
  </div>
  <div id="footer">FOOTER</div>
</div>

最佳答案

将其添加到您的代码中:

#image {
  width: 40px;
  flex-grow: 1; /* new */
}

通常,您可以使用 flex-basis (在本例中相当于 width),并执行以下操作:

#image {
  flex: 1; /* fg:1, fs:1, fb:0 */
}

或者

#image {
  flex: 1 0 40px; 
}

但是,某些浏览器存在一个错误,导致它们忽略嵌套 Flex 容器中的flex-basis。因此 width/flex-grow 组合是一个干净的解决方法。

有关更多详细信息,请参阅我的答案中的“浏览器错误”部分:


下面的演示涵盖了上面回答的问题,以及高度问题 - 宽高比和垂直滚动 - 通过将图像包装在 div 中并在图像上使用绝对定位和 object-fit

在 Chrome、Firefox 和 Edge 中进行了测试。

#mainContainer {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  color: white;
}

#imageContainer {
  flex: 1;
  display: flex;
  justify-content: space-between;
  background-color: green;
}

#image {
  flex-grow: 1;
  position: relative;
}

img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

#previous,
#next {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 25px;
  padding: 0 10px;
  background-color: purple;
}

#title,
#footer {
  text-align: center;
}

#title {
  background-color: blue;
}

#footer {
  background-color: red;
}
<div id="mainContainer">
  <div id="title">TITLE</div>
  <div id="imageContainer">
    <div id="previous">&lt;</div>
    <div id="image">
      <img src="https://pixabay.com/get/52e3dc454f50a414f6d1867dda6d49214b6ac3e45657744e7d2b72dc90/oldtimer-4396528_1920.jpg" />
    </div>
    <div id="next">&gt;</div>
  </div>
  <div id="footer">FOOTER</div>
</div>

jsFiddle

关于html - 如何使图像在 flex 容器中占据最大空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57494910/

相关文章:

html - IE Document Mode在不同的服务器上有不同的默认值

javascript - 通过html/css改变 anchor 标签的href

javascript - 如何将数组的内容输出到 HTML div 容器?

html - ttf 文件无法在 Chrome 和 Firefox 上呈现

Swift - 如何在单击时全屏显示图像,再次单击时如何显示原始大小?

image - 深度学习——同时使用图像和它们的描述

image - JavaFX : Canvas to Image in non GUI Thread

html - 图像未在 div 内对齐

html - 如何选择第一个相邻的 sibling ?

php - 社交引擎无法检查 html