Paul
Paul

Reputation: 319

How to vertically align an image in a container that fills the page?

I'm working on creating an image gallery where an image is centered in the entire page. The horizontal part is of course easy, but the vertical part is giving trouble.

I'm familiar with using display: table-cell; and vertical-align: middle; (or using line-height, but am not having success when using them along with trying to get the element to fill the page.

<div id='contain'>
   <img src='url' />
</div>

I can't set the line-height of #contain since the height of the container will vary based on the size of the window.

If I absolutely position #contain, applying vertical-align:middle no longer centers the image vertically, regardless of how I set the size of the box.

If I try to size #contain to fill the window without absolute positioning, width: 100% and height: 100% (or using min-width/min-height) do not fill the page. Again, I can't specify exact values since they'll vary.

I know I can always set the image to be the background of #contain (or use JavaScript to figure out the heights), but if there's a CSS/HTML way of solving this without tables I'd prefer to use that.

Upvotes: 1

Views: 1195

Answers (1)

algi
algi

Reputation: 577

Try to wrap your img in an extra div and then use the following css:

#contain {
  display: table;
  width: 100%;
  height: 100%;
}
#contain div {
  display: table-cell;
  vertical-align: middle;
}

HTML:

<div id='contain'>
   <div><img src='url' /></div>
</div>

Upvotes: 1

Related Questions