如何使用CSS Flexbox对流体图像和标题进行居中?

Vad*_*din 5 html css image flexbox

请考虑一种布局,其中图像和标题(两者都是可变尺寸)应该在屏幕上居中.

在此输入图像描述

布局应该像这样(参考上图):

  1. 如果图像和标题足够小以适应屏幕,那么没有什么特别的事情发生,它们只是集中在一起.

  2. 如果图像和标题不适合屏幕高度,图像会缩小,直到它们为止.

  3. 如果图像不适合屏幕宽度,它会缩小,直到它完成.

如何使用CSS Flexbox实现这种机制?

更新. 如果标题不适合屏幕,图像应缩小,直到它出现.

在此输入图像描述

Dan*_*eld 5

这是一种方法:

小提琴#1(小图像)

FIDDLE #2(大宽高比)

FIDDLE #3(大高宽比)

html,
body {
  margin: 0;
}
.wpr {
  display: flex;
  align-items: center;
  /* align vertical */
  justify-content: center;
  /* align horizontal */
  height: 100vh;
}
figure {
  text-align: center;
}
figcaption {
  width: 350px;
  text-align: left;
  margin: 0 auto;
}
img {
  max-width: 80vw; /* shrink img to viewport */
  max-height: 80vh; /* shrink img to viewport */
}
Run Code Online (Sandbox Code Playgroud)
<div class="wpr">
  <figure>
    <img src="http://placehold.it/150x80" alt="">
    <figcaption>Caption for the awesome picture Caption for the awesome picture Caption for the awesome picture</figcaption>
  </figure>
</div>
Run Code Online (Sandbox Code Playgroud)


Vad*_*din 0

抱歉,我真的必须更加注意维护这个问题。

看来没有Javascript就无法解决这个问题。我从 @Danield 提出的一个想法开始,应用了一些 Javascript 并提出了以下解决方案。

$figure = $('figure');
$figcaption = $('figcaption');
$img = $('img');

$(window).resize(function() {
  var height = $figure.height() - $figcaption.height();
  $img.css('max-height', Math.max(height, 0));
}).resize();
Run Code Online (Sandbox Code Playgroud)
@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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)