Keep div centered

Discussion in 'JavaScript' started by mathias, Feb 23, 2012.

  1. #1
    Hi there!

    I have a div in html that should always be centered vertically and horizontally. The problem is I'm adding content on to go so the height of the div always changes. Is there any way to keep it nicely centered (I guess this has to be done with javascript)? I can't find some decent samples on the world wide web but if you can find one, please let me know!

    Kind regards!
     
    mathias, Feb 23, 2012 IP
  2. trendint

    trendint Peon

    Messages:
    52
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    jQuery.fn.center = function() {
        var container = $(window);
        var top = -this.height() / 2;
        var left = -this.width() / 2;
        return this
            .css('position', 'absolute')
            .css({ 
                'margin-left': left + 'px',
                'margin-top': top + 'px',
                'left': '50%',
                'top': '50%'
            });
    }
    
    Code (markup):
    Then if you have an id on your div called "keepcentered" for example, you would do

    
    $('#keepcentered').center();
    
    Code (markup):
     
    trendint, Feb 28, 2012 IP
  3. JohnnySchultz

    JohnnySchultz Peon

    Messages:
    277
    Likes Received:
    4
    Best Answers:
    7
    Trophy Points:
    0
    #3
    if you want to vertically align it using css, you'll have a hard time doing it.

    trendint's suggestion would be okay..
     
    JohnnySchultz, Feb 29, 2012 IP