使用自动高度和最大高度垂直居中图像

use*_*241 5 html css html5 frontend css3


我正在尝试使用高度自动垂直居中的图像,因为我想填充水平宽度(100%).它的容器定义为max-height值和overflow-y hidden.

HTML:

<figure>
  <img src="http://lorempixel.com/500/500/" alt="Imagem" />
  <figcaption>
    <p>Sapien elit in malesuada semper mi, id sollicitudin urna fermentum.</p>
  </figcaption>
</figure>
Run Code Online (Sandbox Code Playgroud)

CSS:

figure {
  padding: 5px 0;
  max-height: 300px;
  overflow-y: hidden;
  position: relative;
}
figure>img {
  width: 100%;
  height: auto;
  position: relative;
  top: -50%;
}
figcaption {
  bottom: 0;
  position: absolute;
  background-color: #1e1e1e;
  color: white;
  padding: 5px 10px;
  font-size: 14px;
  text-align: center;
  width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

gop*_*aju 4

尝试这个:

figure > img {
 position: relative;
 margin-top:50%;
 transform:translateY(-50%);
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/kr9q3a0h/1/