With am <img>
(of unknown dimensions) inside a container set to display:flexbox
, is it possible to satisfy the following criteria:
- If the image's native width is smaller than the container's width, it is horizontally centered within the container.
- If the image's native height is smaller smaller than the container's height, it is vertically centered with the container.
- If the image's native width is greater than the container's width, the image is scaled to the width of the container.
- If the image's native height is greater than the container's height, the image is scaled to the height of the container.
I've noticed big disparities between how Chrome and Firefox treat images that are flexbox children. Chrome gets halfway there, but squashes the image vertically. Firefox gets halfway there, but squashes the image horizontally: Codepen
body,
html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.Container {
height: 100%;
width: 100%;
background: red;
display: flex;
justify-content: center;
align-items: center;
}
img{
max-height: 100%;
max-width: 100%;
}
<div class="Container">
<img src="http://d13rap2ac6f4c9.cloudfront.net/image_assets/quarry_medium.jpg?1410945487">
</div>
This is the closest I can get Codepen, which fails on 4.:
body,
html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.Container {
height: 100%;
width: 100%;
background: red;
display: flex;
justify-content: center;
align-items: center;
}
.ImageWrapper {
max-height: 100%;
max-width: 100%;
}
img{
max-height: 100%;
max-width: 100%;
width: 100%;
height: auto;
}
<div class="Container">
<div class="ImageWrapper">
<img src="http://d13rap2ac6f4c9.cloudfront.net/image_assets/quarry_medium.jpg?1410945487">
</div>
</div>
I know that this kind of behaviour was previously impossible without JavaScript, but I'm surprised that it doesn't seem to be achievable using flexbox.
Note: I'm not looking for a JavaScript solution or a solution that doesn't work in modern browsers yet.
In response to David Mann's answer, here is the previous example using object-fit
Codepen.
body,
html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.Container {
height: 100%;
width: 100%;
background: red;
display: flex;
justify-content: center;
align-items: center;
}
img{
max-height: 100%;
max-width: 100%;
object-fit: contain;
}
<div class="Container">
<img src="http://d13rap2ac6f4c9.cloudfront.net/image_assets/quarry_medium.jpg?1410945487">
</div>
Here is a Codepen using the polyfill. Appears to work OK in IE10 but broken in IE11.