user2965241
user2965241

Reputation: 53

Vertically centering an image with auto height and max-height


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%;
}

Upvotes: 5

Views: 4667

Answers (2)

CodeWizard
CodeWizard

Reputation: 142094

You can use this trick: use some pseudo classes to center any unknown content size:

https://css-tricks.com/centering-in-the-unknown/

The trick is to set the content of the before to the full size that you need. This will cause the content to always be centered.

Demo: http://codepen.io/chriscoyier/pen/gsodI

/* This parent can be any width and height */
.block {
  text-align: center;

  /* May want to do this if there is risk the container may be narrower than the element inside */
  white-space: nowrap;
}

/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}
/* This parent can be any width and height */
.block {
  text-align: center;

  /* May want to do this if there is risk the container may be narrower than the element inside */
  white-space: nowrap;
}

/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

Upvotes: 1

gopalraju
gopalraju

Reputation: 2309

Try this:

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

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

Upvotes: 4

Related Questions