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
top
and
left
attributes both equal to
50%
.

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
margin-left
and
margin-top
to -1*(its width) and -1*(its height) respectively. For instance, a
div
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

2 comments:

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

    ReplyDelete
    Replies
    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!

      Delete