2

I have to create a web page that for the purposes of this question is a single image centered both vertically and horizontally in the center of the screen. It has the following requirements:

  • The screen size of the client is unknown (mobile)
  • The image is user-defined and therefore is of unknown dimensions
  • The image must be perfectly centered both vertically and horizontally on all devices
  • The image centering must persist through a screen rotation (i.e. from portrait to landscape)

Being a bit of a CSS newb, I went and created this the only way I knew how, using javascript to position the content: http://jsfiddle.net/error454/8YL9a/

I'm looking for a solution that functions identically to my solution but uses CSS instead of hard equations.

Error 454
  • 7,255
  • 2
  • 33
  • 48
  • What's the benefit of using pure CSS instead of your javascript? – MrGrigg Mar 28 '12 at 21:35
  • What I've shown is the tip of the iceberg for what I really have to create. If I use javascript and a bunch of magic calculations, I will be the product owner for life. I would prefer something that any web developer would be able to maintain in my absence. – Error 454 Mar 28 '12 at 21:41

2 Answers2

2
display:-webkit-box;
-webkit-box-orient:horizontal;
-webkit-box-pack:center;
-webkit-box-align:center;

display:-moz-box;
-moz-box-orient:horizontal;
-moz-box-pack:center;
-moz-box-align:center;

CSS3 property, bad support : webkit, mozilla. Only way to do it with clean markup and CSS without JS.

edit 1 : http://jsfiddle.net/t8qtn/6/

edit 2 : for future proofing, the prefixless version is

display:box;
box-orient:horizontal;
box-pack:center;
box-align:center;
mddw
  • 5,570
  • 1
  • 30
  • 32
0

This is a nice article on centering: http://www.w3.org/Style/Examples/007/center.en.html

It should be something like:

.vcenter { display:table-cell; vertical-align:middle; }
.hcenter { display:block; margin-left:auto; margin-right:auto; }

And then apply both classes to your image:

<img class="vcenter hcenter" src="..."/>

Update: you could simply use a table like here http://www.sorinvasilescu.ro/

evilpenguin
  • 5,448
  • 6
  • 41
  • 49