Vertically center a fluid image in a fluid container

Fer picture Fer · Feb 5, 2011 · Viewed 10.1k times · Source

I certainly do not want to add to the pile of vertical alignments CSS questions, but I've spent hours trying to find a solution to no avail yet. Here's the situation:

I am building a slideshow gallery of images. I want the images to be displayed as large as the user's window allows. So I have this outer placeholder:

<section class="photo full">

(Yes, I'm using HTML5 elements). Which has the following CSS:

section.photo.full { 
    display:inline-block;
    width:100%; 
    height:100%; 
    position:absolute;
    overflow:hidden; 
    text-align:center;
}

Next, the image is placed inside it. Depending on the orientation of the image, I set either the width or height to 75%, and the other axis to auto:

$wide = $bigimage['width'] >= $bigimage['height'] ? true: false; ?>
<img src="<?= $bigimage['url'] ?>" width="<?= $wide? "75%" : "auto"?>" height="<?= $wide? "auto" : "75%"?>"/>

So, we have a fluid outer container, with inside a fluid image. The horizontal centering of the image works, yet I cannot seem to find a way to vertically center the image within it's container. I have researched centering methods but most assume either the container or image has a known width or height. Then there is the display:table-cell method, which does not seem to work for me either.

I'm stuck. I'm looking for a CSS solution, but am open to js solutions too.

Answer

methodofaction picture methodofaction · Feb 6, 2011

This works out fine:

section.photo.full {
  display: table;
  width: 100%;
  height: 100%;
  position: absolute;
  overflow: hidden;
  text-align: center;
}

section.photo.full a {
  outline: 0;
  display: table-cell;
  vertical-align: middle;
}

section.photo.full img {
  margin-top: 0;
}

I'm guessing display table-cell hadn't worked for you because it's parent container wasn't displayed as a table.

Here is a demo in jsfiddle:

http://jsfiddle.net/duopixel/5wzPS/