Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically centering an image with auto height and max-height

Tags:

html

css

frontend


I'm trying vertically center an image that use height auto because I'd like fill the horizontal width (100%). Its container is defined with an max-height value and 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>

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%;
}
like image 758
user2965241 Avatar asked Sep 27 '22 13:09

user2965241


1 Answers

Try this:

figure > img {
 position: relative;
 margin-top:50%;
 transform:translateY(-50%);
}

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

like image 160
gopalraju Avatar answered Oct 07 '22 17:10

gopalraju