Vertically center a fluid image in a fluid container

Posted by Ferdy on Stack Overflow See other posts from Stack Overflow or by Ferdy
Published on 2011-02-05T22:52:48Z Indexed on 2011/02/05 23:26 UTC
Read the original article Hit count: 343

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.

© Stack Overflow or respective owner

Related posts about css

Related posts about vertical-alignment