Recent Posts

Showing posts with label div. Show all posts
Showing posts with label div. Show all posts

CSS: How to align horizontally one div inside another div

How do I horizontally center a div in a div with CSS (if it's possible at all)? The outer div has 100%:

<div id="outer" style="width:100%">  
    <div id="inner">Foo foo</div>
</div>
In this example the outter div have 100% width, to align horizontally the inner div we can apply this code in the inner div:

#inner {
    width: 50%;
    margin: 0 auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing div will work. The margin: 0 auto is what does the actual centering.

If you are targeting IE8+, it might be better to have this instead:

#inner {
    display: table;
    margin: 0 auto;
}
It will make the inner element center horizontally and it works without setting a specific width.




Center a div on the screen with jQuery


jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");
    return this;
}
Now the function call would be:

$(element).center();