Jayr Mendoza Jayr Mendoza - 1 year ago 95
CSS Question

Center LOGO in middle of navigation menu by jQuery & CSS

I have a problem regarding the centered logo on a navigation menu..

I have tried a jquery solution and it's great, however when the menu items is in even numbers the logo won't show up, while it is odd the logo will appear..

can anyone help me solve the problem of the script?

here a sample jsfiddle

/*Center the LOGO*/
var total_menu_items = $('#primary_menu ul li').length; //Get the count of the all menu items
var half_position_even=total_menu_items/2; //If the count is even, just directly divide by 2
var half_position_odd=(total_menu_items+1)/2; //If the count is odd, just adding 1 in order to make it to be an even, then divide by 2
var logo_html='<li class="logo"><a href="#">LOGO</a></li>'; //LOGO HTML

/* Detect the count number is odd or even
If it's divided by 2 and the result is an integer, we will know it's an even, vice versa.
var ex = /^d+$/;
if (ex.test(total_menu_items/2)) {
//When the total number of the menu items is even
$('#primary_menu ul li:nth-child('+half_position_even+')').after(logo_html);
//When the total number of the menu items is odd
$('#primary_menu ul li:nth-child('+half_position_odd+')').after(logo_html);

Answer Source

You should be able to replace all that script with this:

    var total_menu_items = $('#primary_menu ul li').length;
    var middle = Math.ceil(total_menu_items / 2);
      $('#primary_menu ul li:nth-child(' + middle + ')').after('<li class="logo"><a href="#">LOGO</a></li>');

If the number of items is even, then Ceil(n) = n. If odd, it will round it up.

You can use Math.floor() if you want it to round down.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download