简体   繁体   中英

Horizontally and Vertically Center Modal Div IE Issue

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"></script>

<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 http://ajondeck.net/temp/resize.png

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

Example from: Using jQuery to center a DIV on the screen

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM