/ Published in: JavaScript
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// 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'; }