How to centre fluid image and a caption using CSS Flexbox?
Tags: html,css,image,flexbox
Problem :
Please consider a layout where an image and a caption, both of variable dimensions, should be centred on the screen.
Layout should behave like this (consult the figure above):
If an image and a caption are small enough to fit the screen, then nothing special happen and they just get centred.
If an image and a caption doesn’t fit screen height, an image gets shrunk until they do.
If an image doesn’t fit screen width, it gets shrunk until it does.
How to achieve this mechanics using CSS Flexbox?
Update. If the caption doesn't fit the screen, image should shrink until it does.
Solution :
Sorry, I really had to pay more attention maintaining this question.
It seems that the problem could not be solved without Javascript. I've started with an idea proposed by @Danield, applied some Javascript and came up with the following solution.
$figure = $('figure');
$figcaption = $('figcaption');
$img = $('img');
$(window).resize(function() {
var height = $figure.height() - $figcaption.height();
$img.css('max-height', Math.max(height, 0));
}).resize();
@import url("//cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css");
figure {
align-items: center;
display: flex;
flex-direction: column;
height: 100vh;
justify-content: center;
margin: 0;
}
img {
display: block;
max-width: 100vw;
}
figcaption {
flex: none;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<figure>
<img src="http://lorempixel.com/640/480/fashion" />
<figcaption>Whatever the foobar,<br>she said</figcaption>
</figure>