Wednesday, October 14, 2015

How to center a HTML Popup dialog with CSS

In order to create a CSS-only auto-centered dialog, a few steps have to be done.

The first step is to add CSS
position: fixed;
to the target element with its
attributes both equal to

The target element now appears like this:

There is a problem -- setting left and top to 50% does not make it centered. Instead, the element shifted a bit from the center. To solve this, finish step 2 below.

The next step is to adjust the extra pixels shifted from the center. We can set its
to -1*(its width) and -1*(its height) respectively. For instance, a
with width:400px should set
margin-left: -200px
. With this approach, the element shifts back to center and keeps centered all the time.

Note: The element width and height should to be a fixed value.

The following code summarizes the demo:

Here is a Live Demo of this example.

Update 7 Nov 2015: Updated source code section to GitHub version