Tuesday, 16 March 2010

How to horizontally centre align an inner div of unknown width within an outer div of known width :: CSS, JQuery, HTML.

Situation:  You have a an outer div with the id “outer” and an inner div called “inner”.  The menuCont div is of fixed width; let’s say 960 for this example.

The inner div contains variable width elements and you cannot know at design time how many elements and of what width they will be.  You cannot do this with CSS alone (but if you know how, please do share!)

Here’s the solution – it relies on jQuery BTW.

Set the CSS as follows:


And HTML as follows:

<div id="outer">
  <div id="inner" style=”display:none”>
    <!-- Insert variable width elements here -->

And then JavaScript:

$(document).ready(function() {
jQuery.fn.center = function() {
        return this.each(function() {
            var el = $(this);
            var w = el.width();
            var w_box = 960; // TODO: ADD THE CONTAINER WIDTH HERE!
            var w_total = (w_box - w) / 2;
            var css = { "position": 'absolute', "left": w_total + "px" };
$("#inner").fadeIn(); // optional! could use show()

This solution can definitely be improved – but it’s a start.