使图像占据完整高度的flex项目 [英] Make image take full height of flex item

查看:249
本文介绍了使图像占据完整高度的flex项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个容器是100vh(减去固定导航高度)。

I have a container that is 100vh (minus the fixed nav height).

<section class="container">

在这个容器中我有一些文本:

Inside this container I have some text:

 <div class="text">
    <p>title</p>
 </div>

由于内容是动态的,所以可以是任意长度。

Which can be of any length as the content is dynamic.

在此文本下方有一个图片:

Below this text I have an image:

 <div class="image">
    <img src="https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg">
 </div>

图片需要填充100vh( - nav height)容器的剩余部分。

The image needs to fill the rest of the 100vh (- nav height) container.

我使用:

.container{
    display:flex;
    flex-flow: column nowrap;
    ....

小提琴

我遇到的问题是,我需要的图像是其余空间的高度。

The issue I am having is that I need the image to be the height of the rest of the space.

我该如何做?在我的小提琴,如果你的屏幕是小的,它正在被切断,如果你的屏幕是大的,它不填充空间。高度:100%无法正常工作,太大了。

How can I do this? In my fiddle, if your screen is small it is being cut off and if your screen is large it does not fill the space. Height: 100% fails to work, making it too large.

Flex解​​决方案只有请,没有表技巧 - 谢谢!

Flex solutions only please, no table tricks - thanks!

推荐答案

使用高度:100%制作图像容器( .image / code>。

Make the image container (.image) a flex container with height: 100%.

然后,您可以使用 object-fit 微调图像的宽高比和对齐> / object-position

You can then fine-tune the image's aspect ratio and alignment with 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 属性。有关更多详细信息和解决方法,请参阅: http://stackoverflow.com/a/37127590/3597276

Note that the object-fit property is not supported by IE. For more details and a workaround see: http://stackoverflow.com/a/37127590/3597276

这篇关于使图像占据完整高度的flex项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆