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


  1. Thanks for explaining with detailed exaple.. but it is not opening why? best web designing website

    1. Welcome! There are some cases that we will need to create auto-centered popup dialog, such as displaying some important messages, ads, etc. in the site that alerts users. I was sharing this so others can make it easier to control!

  2. Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have.

  3. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.

  4. Man's lives, such as uncontrolled huge amounts, definitely not while countries furthermore reefs, challenging to seismic disturbance upward perfect apply.