我需要使图像在 flex 容器中采用最大尺寸(采用最大宽度或最大高度)。
由于父容器没有固定的宽度和高度,因此我无法使用 max-width
和 max-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"><</div>
<img id="image" src="https://via.placeholder.com/1920x1080" />
<div id="next">></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"><</div>
<div id="image">
<img src="https://pixabay.com/get/52e3dc454f50a414f6d1867dda6d49214b6ac3e45657744e7d2b72dc90/oldtimer-4396528_1920.jpg" />
</div>
<div id="next">></div>
</div>
<div id="footer">FOOTER</div>
</div>
jsFiddle
关于html - 如何使图像在 flex 容器中占据最大空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57494910/