javascript - Centering a dynamically sized div - Stack Overflow

admin2025-04-20  0

Not being a web guy I don't know all the quirks of HTML. I am attempting to center some dynamically sized content inside of a div. This content should always be centered, so I hooked into window.resize to do it. I then manually call window.resize() after applying the CSS to force it to run once.

The problem is that the div does not center horizontally at first, only vertically. Subsequent window resizes force the div to center properly.

Initially I thought that I must be trying to center the div before it was 'ready' as I am calling it first before document.ready fires, but the vertical centering works and I added some trace statements and, sure enough, the left position is being calculated correctly, just not applied (seemingly).

Anyway, this is my first real foray into HTML+CSS, so I'm sure you guys will nail it quickly. Here is some sample html and javascript which reproduces the problem.

Also, my testing has been in Chrome exclusively thus far.

<html lang="en-US">
    <head>
        <script type="text/javascript" src=".7.0/jquery.min.js"></script>         
        <script type="text/javascript">     
            $(function() {
                $(window).resize(function() {
                    var win = $(window);
                    var area = $('#signuparea');
                    $('#signuparea').css({
                        position: 'absolute',                       
                        left: (win.width() - area.outerWidth()) / 2,
                        top: (win.height() - area.outerHeight()) / 2
                    });

                    //$('body').append('<div>l=' + ((win.width() - area.outerWidth()) / 2) + '</div>');                     
                    //$('body').append('<div>w=' + area.outerWidth() + '</div>');
                    //$('body').append('<div>h=' + area.outerHeight() + '</div>');
                });

                $(window).resize();
            });
        </script>
    </head>
    <body style="background-color:0000FF">
            <div id="signuparea">           
                <input type="password">
            </div>      
    </body>
</html>

Not being a web guy I don't know all the quirks of HTML. I am attempting to center some dynamically sized content inside of a div. This content should always be centered, so I hooked into window.resize to do it. I then manually call window.resize() after applying the CSS to force it to run once.

The problem is that the div does not center horizontally at first, only vertically. Subsequent window resizes force the div to center properly.

Initially I thought that I must be trying to center the div before it was 'ready' as I am calling it first before document.ready fires, but the vertical centering works and I added some trace statements and, sure enough, the left position is being calculated correctly, just not applied (seemingly).

Anyway, this is my first real foray into HTML+CSS, so I'm sure you guys will nail it quickly. Here is some sample html and javascript which reproduces the problem.

Also, my testing has been in Chrome exclusively thus far.

<html lang="en-US">
    <head>
        <script type="text/javascript" src="https://ajax.googleapis./ajax/libs/jquery/1.7.0/jquery.min.js"></script>         
        <script type="text/javascript">     
            $(function() {
                $(window).resize(function() {
                    var win = $(window);
                    var area = $('#signuparea');
                    $('#signuparea').css({
                        position: 'absolute',                       
                        left: (win.width() - area.outerWidth()) / 2,
                        top: (win.height() - area.outerHeight()) / 2
                    });

                    //$('body').append('<div>l=' + ((win.width() - area.outerWidth()) / 2) + '</div>');                     
                    //$('body').append('<div>w=' + area.outerWidth() + '</div>');
                    //$('body').append('<div>h=' + area.outerHeight() + '</div>');
                });

                $(window).resize();
            });
        </script>
    </head>
    <body style="background-color:0000FF">
            <div id="signuparea">           
                <input type="password">
            </div>      
    </body>
</html>
Share Improve this question asked Nov 25, 2011 at 20:39 Ed SwangrenEd Swangren 125k24 gold badges188 silver badges268 bronze badges 2
  • It seems that area.outerWidth() returns too big value initially, and therefore signuparea isn't correctly positioned. This is corrected when user resizes the window but not before. github./desandro/masonry/issues/97 suggests that outerWidth has actually innerWidth of parent element. – MetalRain Commented Nov 25, 2011 at 21:09
  • @MetalRain: Thanks for looking into it, but if you unment the trace statements you will notice that the calculated value is initially correct, the div simply doesn't center vertically. Also, that page notes that upgrading to JQuery 1.5 fixes the problem and I am using 1.7. – Ed Swangren Commented Nov 25, 2011 at 21:22
Add a ment  | 

2 Answers 2

Reset to default 5

What about using this code in your window.resize event handler:

$('#signuparea').css({
    position      : 'absolute',                       
    left          : '50%',
    top           : '50%',
    'margin-top'  : '-' + Math.round(area.height() / 2) + 'px',
    'margin-left' : '-' + Math.round(area.width() / 2) + 'px'
});

Since three of the properties set above are static they can be set in CSS:

#signuparea {
    position : absolute;
    top      : 50%;
    left     : 50%;
}

Which makes your JS look like this:

$(function() {
    $(window).resize(function() {
        var area = $('#signuparea');
        $('#signuparea').css({
            'margin-top'  : '-' + Math.round(area.height() / 2) + 'px',   
            'margin-left' : '-' + Math.round(area.width() / 2) + 'px',       
        });
    }).trigger('resize');
});

Here is a jsfiddle of this solution: http://jsfiddle/jasper/Ty6Af/2/

If you give your div a width then margin: 0 auto centers it (zero can be replaced with whatever for top and bottom margin, it is the left/right margin that needs auto.

Sorry, missed that it was absolute. That requires left: 50% with a margin-left: -?? where ?? is half the width of your div.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745114533a285785.html

最新回复(0)