Center "Float:left" Menu


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. // jQuery (method 1):
  2.  
  3. $(function() {
  4. var menu_width = $('#menu').css('float', 'left').width();
  5. $('#menu').css({float : 'none', width : menu_width, margin : '0 auto'});
  6. });
  7.  
  8. // jQuery (method 2):
  9.  
  10. $(function() {
  11. var menu_width = 0;
  12. $('#menu > li').each(function() {
  13. menu_width += $(this).width();
  14. }).parent().css({width : menu_width, margin : '0 auto'});
  15. });
  16.  
  17. // Normal javascript (method 1)
  18.  
  19. window.onload = function() {
  20. var menu = document.getElementById('menu');
  21. menu.style.float = 'left';
  22. var menu_width = menu.offsetWidth;
  23. menu.style.float = 'none';
  24. menu.style.width = menu_width + 'px';
  25. menu.style.margin = '0 auto';
  26. }
  27.  
  28. // Normal javascript (method 2)
  29.  
  30. window.onload = function() {
  31. var menu = document.getElementById('menu');
  32. var items = menu.childNodes;
  33. var menu_width = 0;
  34. for (var i=0; i<items.length; i++)
  35. menu_width += items[i].offsetWidth;
  36. menu.style.width = menu_width + 'px';
  37. menu.style.margin = '0 auto';
  38. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.