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> </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>'); $('#wrapper').wrap(outerWrapper).addClass('innerwrapper'); });
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.