如何使导航居中

How to center the nav

我发现这种在 w3schools (article) 上制作响应式菜单的方法非常简单,但几天来我一直在努力尝试将其水平居中。

html

 <ul class="topnav">
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li class="icon">
    <a href="javascript:void(0);" onclick="myFunction()">&#9776;</a>
  </li>
</ul>

CSS

 /* Remove margins and padding from the list, and add a black background color */
ul.topnav {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

/* Float the list items side by side */
ul.topnav li {float: left;}

/* Style the links inside the list items */
ul.topnav li a {
    display: inline-block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of links on hover */
ul.topnav li a:hover {background-color: #111;}

/* Hide the list item that contains the link that should open and close the topnav on small screens */
ul.topnav li.icon {display: none;}

我根据你的链接代码制作了一个 fiddle:https://jsfiddle.net/gqm7zdf9/

一个可靠的选择是在 UL 周围添加一个包装器,这样您就可以将背景色移到那里。然后你把它放在它的包装纸里。

HTML

<div class="nav-wrapper">
    <ul class="topnav">
        ...
    </ul>
</div>

补充CSS

div.nav-wrapper {
    background-color: #333;
}
div.nav-wrapper ul.topnav {
    display: inline-block;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}


如果您能够(取决于您需要支持的浏览器)使用 display:flex,还有一个更简单的选项。你只需要添加一些 CSS:

ul.topnav {
    /* ... */
    display: flex;
    justify-content: center;
}

https://jsfiddle.net/gqm7zdf9/1/


我认为您可以从那里继续您的媒体查询...