我有一个 100vh 的容器(减去固定导航高度)。
<section class="container">
在这个容器中我有一些文本:
<div class="text">
<p>title</p>
</div>
由于内容是动态的,因此可以是任意长度。
在这段文字下面我有一张图片:
<div class="image">
<img src="https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg">
</div>
图像需要填充 100vh(- 导航高度)容器的其余部分。
我使用:
.container{
display:flex;
flex-flow: column nowrap;
....
我遇到的问题是我需要图像是其余空间的高度。
我该怎么做?在我的 fiddle 中,如果你的屏幕很小,它就会被切断,如果你的屏幕很大,它就不会填满空间。高度:100% 失效,太大了。
请只使用 Flex 解决方案,不要使用表格技巧 - 谢谢!
最佳答案
将图像容器 (.image
) 设为 height: 100%
的 flex 容器。
然后您可以使用 object-fit
/object-position
微调图像的宽高比和对齐方式。
nav {
position:fixed;
background:grey;
width:100%;
height: 100px;
}
main {
padding-top: 100px;
}
.container {
display:flex;
flex-flow: column nowrap;
height: calc(100vh - 100px);
background: green;
border: 3px solid brown;
}
.text { background: yellow; }
/* ***** NEW ***** */
.image {
display: flex;
justify-content: center;
height: 100%;
}
img {
width: 100%;
object-fit: contain;
}
<nav>Nav</nav>
<main>
<section class="container">
<div class="text"><p>title</p></div>
<div class="image">
<img src="https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg">
</div>
</section>
<section class="container">
<div class="text"><p>hello</p></div>
<div class="image">
<img src="https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg">
</div>
</section>
</main>
请注意,IE 不支持 object-fit
属性。有关更多详细信息和解决方法,请参阅:https://stackoverflow.com/a/37127590/3597276
关于html - 使图像占据 flex 元素的全高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37575274/