• 0

[JS] Center a menu that is floated left.


Question

I found the following snippet of javascript (uses jQuery) that would allow me to centre a menu/nav that is set to float:left. It seems to work in IE and Opera OK. But in FF and Safari, it works sometimes and other times trips out (keep refreshing the page and it will eventually work/fail). In Chrome it doesn't work at all.

Here is the code:

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

I don't know js so I can't figure out what the problem is. If anyone can help it would be much appreciated.

Here is the page running the code:

http://www.islandrobot.com/vanessa/

Cheers,

Jordan

15 answers to this question

Recommended Posts

  • 0

Sorry, yes I am trying to centre the entire navigation on that blue strip. Without the js it would be aligned to the left. With the js it should be centred.

P.s. I made an edit to my above post and then deleted it. If you saw the edit, just ignore it ;)

  • 0

That would be the easy way out, yes. But I would rather have it centre automatically since the client may add/remove/rename items from the menu at any time which would mean manually recalculating and changing the width. Since they don't know CSS I wouldn't expect them to have to do that.

  • 0

It wasn't the easy way out when I looked over your code but rather the logical solution to your problem based only on your initial post (which didn't say that the menu would actually be dynamic versus static.)

That being said the best bet is to replace float: left for display:inline. Then you can have all list items centered under the unordered list without needing any javascript.

  • 0
  On 22/04/2010 at 04:26, Cupcakes said:

That being said the best bet is to replace float: left for display:inline. Then you can have all list items centered under the unordered list without needing any javascript.

I tried this method at first but encountered problems with the drop down menus. I couldn't get them to fall directly under their parent li. Instead, the drop-downs always appeared in the far left corner (beginning of the root ul) regardless of which li you were mousing over (if that makes any sense). I played around with it for a while but couldn't get it to behave the way I wanted.

I also tried using inline-blocks which worked nicely except in FF2 which doesn't support it. -moz-inline-box didn't help either because of the drop-down menus.

JS seems like my last and only resort to have a centred, horizontal menu of unknown width and with drop down menus.

  • 0

Hi sweetsam. That seems to have helped a little bit. It at least works in Chrome now sometimes where as it didn't work at all before. However, it is still failing on some page loads. If you keep refreshing the page in FF/Chrome/Safari (Opera and IE seem stable) it will eventually get screwed up. Is this a common problem with javascript? Could it be a jQuery issue?

  • 0

An update:

I've almost got it pegged now. Previously I did not have float:left; applied to #nav (which is the ul). I only had it applied to the li's. As I understood it, the .css('float', 'left') part of the script was trying to add the float to #nav for me??? Well I took that part out and just added float:left; to #nav in the css. This made #nav wrap snug around the li's and allowed for the correct width to be determined. Now everything seems stable in FF.

EDIT: FF is still giving the same problem as Chrome and Safari

Chrome and Safari still seem to be having slight problems getting it perfectly centred though. Sometimes its a bit more to the left and other times it's perfect.

I have also simplified the script down to this:

$(function() {
        var mleft = Math.round(($('#nav-wrap').width#nav').width()) * 0.5);
        $('#nav').css('margin-left', mleft);
});

  • 0

Ok I am pretty sure now that the problem is a simple matter of the calculations being made before the navigation part of the page has been drawn up (if that makes sense). I realize this as some testing showed that occasionally $('#nav-wrap').width() and $('#nav').width() were returning results like 1407 and 1367 respectively. This would also explain why the browsers with faster javascript engines are having the problem more frequently. How can I make sure that the calculations are only made AFTER the html/css has been drawn up by the browser?

Sorry for all these posts, as I said in the beginning I don't know much about js so figuring this out is a whole learning experience :/

EDIT: HOT DAMN.... I guess it was as simple as moving my stylesheet above the javascript. All good now :)

  • 0

To avoid this kind of problem though you should have done this :

$(document).ready(function() {
$(function() {
 var mleft = Math.round(($('#nav-wrap').width#nav').width()) * 0.5);
 $('#nav').css('margin-left', mleft);
});});

It ensures any jquery is applied after the dom has been fully parsed, most of the time the effect is instant.

  • 0

I was actually reading up on the .ready() function when I discovered that I could just move the css above the js.

To quote the .ready() page of the jQuery site that tipped me off:

  Quote
When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

Is it still advisable that I also use the .ready any ways?

  • 0

Yes. But you were using it already. Following pieces of code are equivalent. The problem was being caused by the fact that the styles were being applied after the script swung in to action. Scripts should always be the last to run and more importantly should be included after the stylesheets. Sometimes you will see scripts attached to the end of the document for the same reason.

$(function(){

})

and

$(document).ready(function(){

})

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I happen to try it today not knowing about the update and was happily surprised; it is great.
    • Hello, Hardware Support Applications are a special kind of Microsoft Store app and have to go through additional checks and certifications because they can communicate directly with their driver, which means that a vulnerability in one of them could allow an attacker access to kernel space memory through the HSA ←→ device driver interface.  In other words, a BYOVD (bring your won vulnerable driver) attack, but with the HSA being used as an extra step. Remember, the Microsoft Store is strategic to Microsoft's long-term goals: they see it as the means to get the same 30% of every application sale that Apple and Google get through their stores, which is why it has been a fixture of Windows since Windows 8 was introduced in 2012 despite a low adoption rate.  Microsoft cannot afford to have anyone get an app through their store which causes a security issue for their end users.  Even if the app was written by and uploaded to the Microsoft Store by a partner, it is Microsoft's name on the store, and they are the ones that will have reputational/brand damage if they allow something malicious into their store. Regards, Aryeh Goretsky  
    • This is more from my childhood, when nickelodeon just launched and had to license shows to have something to air. Left a big an impact, but probably more emotion positive / childhood thing. Europe got the follow up season's decade's latter with the animation studio that did Air Bender but never licenses for the US. I miss the day's of longer intro's. Nier (PS3) Intro is epic, and was very unexpected.  PS1 Xengears was also epic and an amazing game.  
    • Sayan Sen, do you think one day an image of the Windows Vista desktop or the wallpaper could be used in the primary image of an article? (When I think of CDs and DVDs I think of that release of Windows and of earlier releases; it is the one that debuted IMAPI 2.0 and other features.)
    • Big fan of EAC Here's a good non-default naming scheme I found on the web (can't take credit) File Name Scheme - %albumartist%\%year% - %albumtitle%\%tracknr2% %title% Various Artists Naming Scheme - Various Artists\%year% - %albumtitle%\%tracknr2% %title% Also, I need test but there is a new flac.exe binary & dll you can drop in the folder to upgrade flac support. I did this pre EAC 1.8. EAC 1.8 did upgrade it to 1.4.3. Flac 1.5.0 came out this year. https://ftp.osuosl.org/pub/xiph/releases/flac/ I don't know how much of a difference / impact will make.
  • Recent Achievements

    • Week One Done
      Ricky Chan earned a badge
      Week One Done
    • Week One Done
      maimutza earned a badge
      Week One Done
    • Week One Done
      abortretryfail earned a badge
      Week One Done
    • First Post
      Mr bot earned a badge
      First Post
    • First Post
      Bkl211 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      484
    2. 2
      +FloatingFatMan
      263
    3. 3
      snowy owl
      240
    4. 4
      ATLien_0
      227
    5. 5
      Edouard
      188
  • Tell a friend

    Love Neowin? Tell a friend!