views:

213

answers:

2

I'm trying to horizontally and vertically center a modal window inside a div. I want it to be cross browser compatible. You can see from the picture below that when I resize IE8 then click, "show modal" button it displays not exactly horizontally centered. This does not seem to be an issue with Chrome. Any thoughts? How would you guys accomplish this?

<html>
<head>
<title>test</title>
<style type="text/css">
    *
    {
        margin: 0px;
        padding: 0px;
    }
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;

<script type="text/javascript">

    $(function() {

        $('#modal').click(function() {

            // overlay
            $('<div id="overlay" />').css({
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                backgroundColor: 'black',
                opacity: 0
            }).appendTo('body');

            $('<div id="datamodal" />').css({
                backgroundColor: '#FFFFFF',
                border: '10px solid #999',
                height: '200px',
                width: '600px',
                position: 'absolute',
                top: '50%',
                left: '50%',
                marginTop: '-120px', 
                marginLeft: '-320px',
                color: '#111111',
                fontWeight: 'bold',
                padding: '10px',
                display: 'none'
            }).append('<input type="text" />').appendTo('#overlay');

            $('#overlay').fadeTo(300, 0.7);
            $('#datamodal').fadeIn(300);
        });

    });

</script>

</head>
<body>
    <input id="modal" type="button" value="show modal" />
</body>
</html>

alt text

+1  A: 

You need to calculate the position based on the window and dialog size and set the style via JavaScript.

Example from: http://stackoverflow.com/questions/210717/what-is-the-best-way-to-center-a-div-on-the-screen-using-jquery

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}
Diodeus
Ok... how exactly is that done?
aherrick
See my edits. :)
Diodeus
+1  A: 

After messing around with the CSS for a long time and scratching my head, I noticed that the document doesn't have a DOCTYPE. I added a Strict DOCTYPE and suddenly IE8 started behaving with the rest of your code untouched.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
Greg W