Centralize Horizontal Menu Bar

Discussion in 'CSS' started by kertoon, Jul 1, 2014.

  1. #1
    This is my code:
    <style type="text/css">
    ul#navbar {
    list-style-type: none;
    margin: 0;
    padding: 0;
    }
    ul#navbar li {
    float: left;
    border: 1px solid black;
    text-align: center;
    }
    ul#navbar a {
    background-color: #CCC;
    color: #000;
    text-decoration: none;
    display: block;
    width: 120px;
    padding: 4px;
    }
    ul#navbar a:hover {
    background-color: #CFF;
    text-decoration: underline;
    }
    ul#navbar ul {
    display: none;
    list-style-type: none;
    }
    ul#navbar li:hover ul {
    display: block;
    position: absolute;
    margin: 0;
    padding: 0;
    }
    ul#navbar li:hover li {
    float: none;
    }
    </style>
     
    kertoon, Jul 1, 2014 IP
  2. kk5st

    kk5st Prominent Member

    Messages:
    3,497
    Likes Received:
    376
    Best Answers:
    29
    Trophy Points:
    335
    #2
    One possible solution:
    ul#navbar {
      ... ;
      display: table;
      margin: 0 auto;
      }
    Code (markup):
    An element displayed as table will shrink wrap its content. Auto margin will then center it horizontally.

    cheers,

    gary
     
    kk5st, Jul 1, 2014 IP
  3. kertoon

    kertoon Well-Known Member

    Messages:
    187
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    133
    #3
    Thank you.
     
    kertoon, Jul 1, 2014 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #4
    don't float anything, set text-align:center on the outermost UL, set the anchors to display:inline-block and the LI to display:inline; You go that route you'll also want to pull the BORDER off the LI and put it on the anchor since border on a inline is unpredictable.

    I also suggest NOT using display:none to hide the dropdowns, screen readers may ignore them and it makes already painfully difficult keyboard navigation even harder. Try using overflow:hidden on the LI, or left:-999em and :hover left:0 on the dropdown. Either of those techniques is "safer" from an accessibility standpoint.

    Though personally, I've pulled the plug on dropdown menus altogether; they're accessibility trash and a pain in the ass on smaller displays when you start making the layout responsive.
     
    deathshadow, Jul 4, 2014 IP
  5. kertoon

    kertoon Well-Known Member

    Messages:
    187
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    133
    #5
    Thank you.
     
    kertoon, Jul 5, 2014 IP