How to centrally align a float: left ul/li navigation menu with css?

后端 未结 10 1103
深忆病人
深忆病人 2020-12-28 14:57

So I have the following CSS in place to display a horizontal navigation bar using:

.navigation ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.naviga         


        
相关标签:
10条回答
  • 2020-12-28 15:03
    ul {
     display: inline-block;
     text-align: center;
    }
    
    0 讨论(0)
  • 2020-12-28 15:04
    .navigation ul 
    {
      list-style-type: none;
      padding: 0px;
      width: 200px;
      margin: 0 auto;
    }
    
    0 讨论(0)
  • 2020-12-28 15:07
    style="position: absolute; z-index: 1;"
    
    0 讨论(0)
  • 2020-12-28 15:10

    Give your .navigation ul a width and use margin:0 auto;

    .navigation ul 
    {
      list-style: none;
      padding: 0;
      width: 400px;
      margin: 0 auto;
    }
    
    0 讨论(0)
  • 2020-12-28 15:10

    You could set the <li>'s to be display: inline, then set text-align: center on the <ul>. Doing that, you can remove the float: left from the list items and you don't need to have a fixed width for the navigation bar as you would if you used margin: 0 auto.

    <html>
      <head>
        <style>
          ul { 
            list-style: none;
            text-align: center;
          }
    
          li {
            display: inline;
            margin: 0 1.15em;
          }
        </style>
      </head>
    
      <body>
        <ul>
          <li>Option 1</li>
          <li>Option 2</li>
          <li>Option 3</li>
        </ul>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-12-28 15:15

    Well, to use margin:0 auto on something, it must have a defined width. Probably the best workaround is:

    ul li {
      display: inline;
      list-style-type: none;
    }
    ul {
      text-align:center;
    }
    
    0 讨论(0)
提交回复
热议问题