Search code examples
jqueryipadjquery-mobilemobile-safarivertical-alignment

Centering a fixed height/width dialog on screen of variable window size


I am attempting to center a dialog that has fixed height and width (750x360) on the screen using jquery mobile and CSS3 (without javascript calculations). This will be run on IPad mobile safari and so far I have not found a version of calc() that works on that browser.

I am currently centering by calculating margin-top using javascript. Params being the variable height of the window and fixed height of the dialog. However I need to remove this from my implementation to meet standards, and only use CSS/jquery methods if possible.

Is there a way to do this?

I am importing both jquery UI and jquery mobile libraries, so I have access to all their methods.


Solution

  • Here's an example on how to center a div vertically and horizontally:

    #center {
       background-color: red;
       width: 100px;
       height: 100px;
       position: absolute;
       top: 50%;
       left: 50%;
       margin-top: -50px; /* half the height */
       margin-left: -50px; /* half the width */        
    }​
    

    Example on jsfiddle

    To position an element you use position:absolute this way you can specify where the element should be without having to worry about other elements. To center the element we want to position it on 50% on the container size. But if we stop there the element top left corner will be centered. Therefore we have to add the margin's.

    Hope this can help you in the right direction.