Centering HTML Elements on Screen

This is the fastest and easiest method I have seen yet to center an HTML element on the screen.

Give the element a height and width. Then set the position to fixed, and left and top elements at 50%. Then the trick comes into play….negative margins!!! Give margin-top and margin-left a negative margin of half the width size of the element.  ….. Okay that was kind of confusing…check out this exapmle and you’ll get it:

center-div

And of course, if you need to make this dynamic width / height…you can always use your trusty friend JavaScript to apply the CSS styles dynamically. This method works great for the Modal Dialog type of scenario. Using this idea alongside JQuery and BlockUI makes this scenario no problem to manage.

*Note – thanks to Dirty Steve again for this CSS trick…you are ever so wise with your negative margins.