2016-06-21 35 views
0

我發現這個非常簡單的方法來在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;} 
+0

[這個](http://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_topnav)是我使用的代碼 – Dino

回答

0

我做了一個小提琴從您鏈接代碼: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%); 
} 


如果你能(取決於你所需要支持的瀏覽器)給我們e display:flex,還有更簡單的選擇。你只需要添加一些CSS

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

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


我想你就可以繼續從那裏您的媒體查詢...

+0

第一個解決方案由於某種原因沒有工作,但我使用了第二個,它完美的工作。謝謝 – Dino

+0

@Dino:您可以自由地將答案標記爲已接受。謝謝。 ---如果您需要更多指導或幫助,請告訴我。 ***':)'*** – Seika85