3

I have a div like this:

<div class="first">
<img src="image/image1.gif" style="width:30%;display:inline-block"/> 
<img src="image/image2.gif" style="width:30%;display:inline-block"/> 
<img src="image/image3.gif" style="width:30%;display:inline-block"/>
<br />testing<br /><br />がらんどう
</div>

I want it to vertically center and resizable so I use standard JQuery code:

$(window).resize(function(){

$('.first').css({
    position:'absolute',
    top: ($(window).height() - $('.first').outerHeight())/2
});
});

$(window).resize();

The css for the div is like this:

.first
{
position:absolute;
top:50%;
}

The problem is: The div is not vertically centralized upon loading, but when u resize the window, it will be centralized..

Can you guys help me figure out? Thanks!!

4

2 に答える 2

2

You have your .resize() call inside of $(document).ready(), right? Otherwise, none or many elements won't be ready/available. You probably want:

$(document).ready(function () {
    $(window).resize(function(){
        $(".first").css({
            position:'absolute',
            top: function () {
                return ($(window).height() - $(this).outerHeight())/2;
            }
        });
    });
    $(window).resize();
});

Also, you want to use $(this).outerHeight() instead of $('.first').outerHeight()

Since some browsers fire resize very often during resizing (some only fire it at the end of a resize), it might be "better" to cache the jQuery window object:

$(document).ready(function () {
    var $window = $(window);
    $window.resize(function(){
        $('.first').css({
            position:'absolute',
            top: function () {
                return ($window.height() - $(this).outerHeight())/2;
            }
        });
    });
    $window.resize();
});
于 2013-04-04T03:32:56.277 に答える