Flexbox 响应问题中的图像
Img inside Flexbox responsitivity issue
我有一段代码 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 上,当我垂直调整 window 大小时,图像仅在垂直方向上有响应。宽度与高度不成比例变化(在这种情况下会减小)。在 Firefox 上一切正常。
你知道这个问题吗?
如果容器要占据整个屏幕大小,您可以使用 viewports units。并且不要忘记为 html 和正文标签设置 height
。
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
使图像居中。
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 并查看下面的相关评论。
我有一段代码 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 上,当我垂直调整 window 大小时,图像仅在垂直方向上有响应。宽度与高度不成比例变化(在这种情况下会减小)。在 Firefox 上一切正常。
你知道这个问题吗?
如果容器要占据整个屏幕大小,您可以使用 viewports units。并且不要忘记为 html 和正文标签设置 height
。
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
使图像居中。
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 并查看下面的相关评论。