Tom Lehman
Tom Lehman

Reputation: 89313

Display one image (of unknown dimensions) centered (vertically and horizontally) on the page

How do I center a single image vertically and horizontally without knowing its dimensions ahead of time?

Also, if the image is larger than the view-port, it should re-size to fit

Is there any way to accomplish all of this without using Javascript?

Upvotes: 2

Views: 7798

Answers (2)

ronalchn
ronalchn

Reputation: 12335

You can only vertical align if the containing element is of display: table-cell, so set that, and then you can use vertical-align and text-align. Here is an example:

​<div style="width: 500px; height: 300px; border: 1px red solid; display: table-cell; vertical-align: middle; text-align: center">
<img src="https://www.google.com/images/srpr/logo3w.png">
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Example fiddle: http://jsfiddle.net/8Aq5Y/

It does not work if you do not change the display, or if the display is set to something like block or inline.

To make sure it fits in the containing element, just use max-width and max-height:

<div style="width: 100px; height: 100px; border: 1px red solid; display: table-cell; vertical-align: middle; text-align: center">
<img src="https://www.google.com/images/srpr/logo3w.png" style="max-width: 100px; max-height: 100px;">
</div>​

http://jsfiddle.net/8Aq5Y/3/

Upvotes: 5

zenkaty
zenkaty

Reputation: 1548

Here's a page I made earlier doing just this :)

http://kt80.net/

This is the whole code:

body{background:#e5e7e6 url(egyptrabbit.jpg) no-repeat fixed 50% 50%}

EDIT: Ah, just saw the resize to fit part. You can use the CSS3 attribute "contain" on the background image to make sure it's always within the window, but this will stretch it if the window is bigger.

Upvotes: 9

Related Questions