【问题标题】:Img inside Flexbox responsitivity issueFlexbox 响应问题中的图像
【发布时间】:2015-08-06 04:38:06
【问题描述】:

我有一个带有flex div 的代码片段,里面有一个img

html, body {
  height: 100%;
  margin: 0;
}
.container {		
  display: flex;
  align-items: center;
  justify-content: center;		
  width: 100%;
  height: 100%;
  background: black;
}
.item {
  max-height: 100%;
  max-width: 100%;		
}
<div class="container">
  <img src="http://i.stack.imgur.com/aHBI2.png" class="item">
</div>

在 Chrome 和 IE 上,当我垂直调整窗口大小时,图像仅在垂直方向上响应。宽度不与高度成比例变化(在这种情况下减少)。在 Firefox 上一切正常。

你知道这个问题吗?

http://jsfiddle.net/z2v9o9ew/1/

【问题讨论】:

    标签: html css responsive-design flexbox


    【解决方案1】:

    如果容器要占据整个屏幕大小,您可以使用viewports units。并且不要忘记为 html 和 body 标签设置height

    http://jsfiddle.net/hsn43uzq/

    html, body {
        height: 100%;
        margin: 0;
    }
    .container {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        background: black;
    }
    .item {
        max-width: 100vw;
        max-height: 100vh;
    }
    <div class="container">
        <img src="http://dummyimage.com/500" class="item" />
    </div>

    作为一种解决方法,您可以删除 flex,并使用 css transform 使图像居中。

    http://jsfiddle.net/5k84mfft/

    html, body {
        height: 100%;
        margin: 0;
    }
    .container {
        width: 100%;
        height: 100%;
        background: black;
        position: relative;
    }
    .item {
        max-width: 100%;
        max-height: 100%;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }
    <div class="container">
        <img src="http://dummyimage.com/500" class="item" />
    </div>

    编辑:问题也可以通过简单地按照 OP 的建议添加来解决,尽管我们不知道它为什么会起作用。

    flex-direction: column;
    

    Updated demo 并查看下方的相关 cmets。

    【讨论】:

    • 在这种情况下效果很好。但我需要 img 始终适合它的容器。例如,我想将 .container 的宽度和高度设置为 50%。在这种情况下,img 正在转义容器
    • 可以用background-size: contain的背景图片吗?
    • img 可能会被调高,希望避免这种行为
    • 我想避免第二种方法,但你猜不到!我问过freenode css irc,他们说要添加: flex-direction: column;它起作用了...... css很奇怪。只需在升技旧版浏览器上进行测试即可。
    • 太棒了flex-direction: column; 就这样!很高兴知道。好吧,flex 不能在旧的 IE 上工作,你必须使用前缀才能让它在 Safari 上工作(是的,即使是最新版本) - caniuse flexbox
    猜你喜欢
    • 2021-09-13
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 2016-03-03
    相关资源
    最近更新 更多