Return to Snippet

Revision: 10698
at January 9, 2009 18:09 by corey


Initial Code
// jQuery (method 1):

$(function() {
  var menu_width = $('#menu').css('float', 'left').width();
  $('#menu').css({float : 'none', width : menu_width, margin : '0 auto'});
});

// jQuery (method 2):

$(function() {
  var menu_width = 0;
  $('#menu > li').each(function() {
    menu_width += $(this).width();
  }).parent().css({width : menu_width, margin : '0 auto'});
});

// Normal javascript (method 1)

window.onload = function() {
  var menu = document.getElementById('menu');
  menu.style.float = 'left';
  var menu_width = menu.offsetWidth;
  menu.style.float = 'none';
  menu.style.width = menu_width + 'px';
  menu.style.margin = '0 auto';
}

// Normal javascript (method 2)

window.onload = function() {
  var menu = document.getElementById('menu');
  var items = menu.childNodes;
  var menu_width = 0;
  for (var i=0; i<items.length; i++)
    menu_width += items[i].offsetWidth;
  menu.style.width = menu_width + 'px';
  menu.style.margin = '0 auto';
}

Initial URL


Initial Description
This enables you to center a horizontal unordered list that uses "float:left". Normally, this is almost impossible with pure CSS, but Javascript makes it easy. jQuery makes it even easier.

Initial Title
Center "Float:left" Menu

Initial Tags
javascript, jquery, center

Initial Language
JavaScript