开发者

JQuery Vertical Align Function

I found a css trick on the internet and to vertically align an element(link: http://www.vdotmedia.com/blog/vertically-center-content-with-css/ , not exactly the same but the same idea.).

I decided to put it 开发者_运维问答into a jquery function:

    $.fn.centreVertical = function()
    {
        $(this).wrap(                                                                                                                                        //centered element
            $("<div/>").css({'position':'relative','top':'-50%'}).wrap(                                                                         //child
                $("<div/>").css({'position':'absolute','top':'50%','display':'table-cell','vertical-align':'middle'}).wrap(        //parent
                    $("<div/>").css({'margin':'auto','display':'table','height':'100%','position':'relative','overflow':'hidden'}) //grandparent 
                 )
             )
          );
    };

My problem is that it wraps only the element (aka 'this') in the first div, the rest of the wraps don't seem to take effect, i checked the html and i only see the first div and the element.

Anyone know why this is so? Perhaps there is a better way to do this?


I can't speak to whether your technique will do as you wish, but if you want to wrap your element in the divs in the order you specify, you want to add parent() calls to your chain so you're wrapping the right element:

$.fn.centreVertical = function() {
  $(this).wrap('<div/>').css({
    'position': 'relative',
    'top': '-50%'
  }).parent().wrap('<div/>').css({
    'position': 'absolute',
    'top': '50%',
    'display': 'table-cell',
    'vertical-align': 'middle'
  }).parent().wrap('<div/>').css({
    'margin': 'auto',
    'display': 'table',
    'height': '100%',
    'position': 'relative',
    'overflow': 'hidden'
  });
};

The other thing I'd recommend is to just define some classes with the styles you want to apply to the div then just call addClass() on the element rather than defining the css properties directly which will add them as style attributes to the elements.

Additionally, use inspect element or use the view source | view generated source from the Web Developer toolbar add-on to FF to make sure you're looking at the dom as it exists rather than the html source which won't show dynamically added elements.


function alignVertical(){
    $('.align-vertical').each(function() {
        var that = $(this);
        var height = that.height();
        var parentHeight = that.parent().height();
        var padAmount = (parentHeight / 2) - (height/2);
        that.css('padding-top', padAmount);
    });   
}

just use class align-vertical and this function use on window load!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜