Search code examples
javascriptcssenyo

Centering an image on screen using CSS - Random Screen/Image dimensions


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.


Solution

  • 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;