Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image inside flex-item ignores max-height:100% in chrome and firefox - (works in safari)

Tags:

css

flexbox

I want an image to fill either the width or height of the window-size/viewport.

For a better understanding of what i’m trying to do, i’ve created an example on codepen - please check out and resize the preview. It works fine in safari but chrome and firefox seems to have problems. The image ignores the max-height property and overflows the flex-item dimensions.

Any suggestions to get this work in chrome and firefox?

html,
body {
  height: 100%;
}
.flex-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: green;
}
.flex-item {
  max-width: 100%;
  max-height: 100%;
}
img {
  max-width: 100%;
  max-height: 100%;
}
<div class="flex-container">
  <div class="flex-item">
    <img src="http://i.stack.imgur.com/mrEyQ.jpg">
  </div>
</div>
like image 608
durchgemacht Avatar asked May 05 '15 14:05

durchgemacht


1 Answers

The problem is that both the image and its containing block have

max-height: 100%;

Instead, remove the max for the containing block:

.flex-item {
    width: 100%;
    height: 100%;
}

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

However, note that .flex-item will be centered inside .flex-container, but the image won't be centered inside .flex-item.

To fix that, you can use the centering in the unknown technique (or alternatively, flexbox).

html,
body {
  height: 100%;
  margin: 0;
}
.flex-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: green;
}
.flex-item {
  width: 100%;
  height: 100%;
  text-align: center;
}
.flex-item:after {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
img {
  max-width: 100%;
  max-height: 100%;
  vertical-align: middle;
}
<div class="flex-container">
  <div class="flex-item">
    <img src="http://i.stack.imgur.com/mrEyQ.jpg">
  </div>
</div>
like image 175
Oriol Avatar answered Nov 13 '22 05:11

Oriol