Vertically align div (no tables)

后端 未结 8 1306
孤街浪徒
孤街浪徒 2020-12-02 17:38

I can horizontally align a div and all the content looks nice. Looking to vertical align a div that does not contain any tables. I tried setting margin positions to some neg

8条回答
  •  不思量自难忘°
    2020-12-02 18:06

    Unless you have the ability to explicitly set the height of your container (which doesnt look like that's the case), there is no cross browser solution for vertically centering your DIV container.

    Using a table is completely viable, but you have noted that this cannot be used.

    If javascript is an option, we could easily remedy this for you. A jQuery plugin already exists for vertically aligning a container.

    (function ($) {
        // VERTICALLY ALIGN FUNCTION
        $.fn.vAlign = function() {
            return this.each(function(i){
                var ah = $(this).height();
                var ph = $(this).parent().height();
                var mh = (ph - ah) / 2;
                $(this).css('margin-top', mh);
            });
        };
    })(jQuery);
    

    And you would vertically align a DIV block like so:

    $('#example').vAlign();
    

    Taken from Simple Vertical Align Plugin.

提交回复
热议问题