Centering boxes with jQuery

Centering boxes with jQuery is a pretty straightforward task. Let's start with a basic markup like this:

<div id="wrapper">

    <div class="box">Test box</div>
    <div class="box">Test box</div>
    <div class="box nomargin">Test box</div>


Then we prepare our CSS styles:

.box {
    width: 100px;
    height: 100px;
    background: yellow;
    border: 1px solid orange;
    line-height: 100px;
    text-align: center;
    float: left;
    margin-right: 5px;


.innerwrapper {

    width: 322px;
    overflow: hidden;
    margin: 0 auto;
    padding: 0;


.outerwrapper {

    width: 600px;
    margin: 0 auto;
    padding: 2em 0;
    border: 2px solid green;
    overflow: hidden;


.normargin {

    margin-right: 0 !important;


Finally, we add jQuery:

$(document).ready(function() {

    var outerWrapper = $('<div class="outerwrapper"></div>');


That's pretty simple: we've wrapped our container with an outer element. Then we've centered our container by adding the CSS class innerwrapper to it. You can see the final result here.

Screenshots taken from Internet Explorer

IE 8

IE 7

IE 6

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.