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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.