简体   繁体   中英

javascript function to vertically center element

I'm trying to write a function to vertically center elements if they have a class called "vcenter(#)". For example, vcenter1 vcenter2. It's supposed to take the element's parent's innerheight and subtract the element's innerheight then divide by 2. The value then is applied to the css as the margin-top. It doesn't work though. Please help!

$(document).ready(function(){
    for (i=1; i<3; i++){
        var childID = $(".vcenter" + i);
        var parent = childID.parent().innerHeight();
        var child = childID.innerHeight();
        var marginTop = (parent - child)/2 + 'px';
        $(childID).css({"margin-top", marginTop})
    }
});

How about this... http://jsfiddle.net/mVn9S/

$(document).ready(function () {
    $('.vcenter').each(function () {
        var parent = $(this).parent().innerHeight();
        var child = $(this).innerHeight();

        $(this).css({
            'margin-top': ((parent - child) / 2) + 'px'
        });
    });
});

Have you considered using CSS3 Flexbox with a polyfill for old versions of IE? Might be less work.

Change your code to look like this:

$(document).ready(function(){
    for (i=1; i<3; i++){
        var childElement = $(".vcenter" + i);
        var parent = childElement.parent().innerHeight();
        var child = childElement.innerHeight();
        var marginTop = (parent - child) / 2;
        childElement.css({"margin-top": marginTop});
    }
});

Notice use of ; at the end of lines - it's a good habit even in JS.

I don't know how your HTML looks but probably this could be easily generalized for all elements with .vcenter class:

$(document).ready(function(){
    $('.vcenter').each(function() {
        var childElement = $(this);
        var parent = childElement.parent().innerHeight();
        var child = childElement.innerHeight();
        var marginTop = (parent - child) / 2;
        childElement.css({"margin-top": marginTop});
    });
});

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