jQuery UI dialog centering ultimate fix

UPDATE OCTOBER 2014: jQuery UI was recently updated and the dialogs finally position correctly at the center of the screen! Don't specify any position for your dialog and it'll in the right place by default. Glad they got that sorted out!

[This post is now obsolete]
I have been having issues positioning jQuery UI dialogs for a long time.
What I expect from a modal dialog is simple:

  • it must be centered on the screen
  • if I scroll the page, the dialog should still be at the center of the screen (fixed position)
  • when I invoke the dialog for example by clicking a link, the page must not scroll either
  • when I close the dialog, the page must not scroll up or down

Simple requirements you say; though for some reason I haven't been able to achieve this with basic jQuery UI functions. I would *always* have at least one of the following issues, even after trying a good number of fixes recommended online:

  • dialog shows up off screen (scrolling is required to be able to see the dialog)
  • dialog is not centered on the screen
  • when the dialog is opened, the page scrolls up or down
  • when the dialog is closed, the page scrolls up or down
  • combinations of several of the above issues
After spending hours trying to figure out what was wrong with my code, I have finally been able to solve my problem in what seems to be a permanent way. I have been able to successfully achieve the desired effect: keep my modal dialog centered on the screen, without scrolling the page at all.

jQuery Center Dialog plugin

The solution I have found is to use a jQuery plugin called jQuery center by Andreas Lagerkvist. However you need to know a few things before you can use it.

Step 1: include the script into your page:
It is of course better to download the script and host it locally, but if you just want to give this a try, a direct link shouldn't hurt.

Step 2: When initializing your dialog, affect an arbitrary class to the dialog and set its position to "center":
  $( "#dialog-login" ).dialog({
    autoOpen: false,
    height: 280,
    width: 400,
    modal: true,
    dialogClass: 'dlgfixed',
    position: "center",
    buttons: {

Step 3: at the end of your page, invoke the code for centering your dialog:
The argument of the center() function must be set to false in order to give the dialog a fixed position.

This worked like a charm for me, I hope it will work for you too. Also note that there are probably a hundred different ways to do this, but you must admit this is pretty simple.

Search This Blog