Vertically center two divs inside a wrapper (with dynamic content and content below the wrapper)

前端 未结 4 1205
孤城傲影
孤城傲影 2020-12-08 08:02

I\'m trying to center two divs with dynamic heights inside a dynamic wrapper... I\'ve been playing with all sorts of tricks to try and get this working cross-browser to no a

4条回答
  •  一生所求
    2020-12-08 08:33

    So I've had a quick poke at your question, it's not a very big jQuery solution, in fact it's so simple that even i could do it !

    What i did was worked out which div is bigger dynamically (i.e. is red or green bigger), we then ignore the bigger div and work out the correct vertical margin for the smaller div.

    View this example for a better understanding: http://jsfiddle.net/6fN48/

    CSS

     #wrapper
    { width: 400px; border: 1px solid blue; padding: 10px; margin: 0 auto; }
    
    #wrapper .red
    { width: 195px; float: left; border: 1px solid red; }
    
    #wrapper .green
    { width: 195px; float: right; border: 1px solid green; }
    

    jQuery

    var r = $('#wrapper .red').outerHeight();
    var g = $('#wrapper .green').outerHeight();
    var w = $('#wrapper').outerHeight();
    
    /* calculate which is bigger and apply the margin to that element */
    
    /* is the red or green div bigger? */
    if(r > g){
    
        /* ok red is bigger, then work out the top margin to apply onto green */
        var x = (w - g) / 2;
    
        /* apply CSS to the green div */
        $('#wrapper .green').css({ 'margin-top' : x + 'px' });
    
    } else if(r < g){
    
         /* ok green is bigger, then work out the top margin to apply onto red*/
        var x = (w - r) / 2;
    
        /* apply CSS to the red div */
        $('#wrapper .red').css({ 'margin-top' : x + 'px' });
    
    }
    

    HTML

    Lorem ....
    Lorem ipsum dolor ...

    I hope this helps, the only other way is to use css positioning with a known height, which obviously is not dynamic. :)

提交回复
热议问题