如何創建:居中的頂部導航

學習如何創建帶有居中鏈接/徽標的導航欄。

親自試一試

創建頂部導航欄

第一步 - 添加 HTML:

<!-- 頂部導航 -->
<div class="topnav">
  <!-- 居中鏈接 -->
  <div class="topnav-centered">
    <a href="#home" class="active">Home</a>
  </div>
  <!-- 左對齊鏈接(默認) -->
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <!-- 右對齊鏈接 -->
  <div class="topnav-right">
    <a href="#search">Search</a>
    <a href="#about">About</a>
  </div>
</div>

第二步 - 添加 CSS:

/* 為頂部導航添加黑色背景色 */
.topnav {
  position: relative;
  background-color: #333;
  overflow: hidden;
}
/* 設置導航欄中鏈接的樣式 */
.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}
/* 更改鼠標懸停時鏈接的顏色 */
.topnav a:hover {
  background-color: #ddd;
  color: black;
}
/* 為活動/當前鏈接添加顏色 */
.topnav a.active {
  background-color: #04AA6D;
  color: white;
}
/* 頂部導航內的居中部分 */
.topnav-centered a {
  float: none;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
/* 頂部導航內的右對齊部分 */
.topnav-right {
  float: right;
}
/* 響應式導航菜單 - 在移動設備上將鏈接堆疊顯示,而不是并排顯示 */
@media screen and (max-width: 600px) {
  .topnav a, .topnav-right {
    float: none;
    display: block;
  }
  .topnav-centered a {
    position: relative;
    top: 0;
    left: 0;
    transform: none;
  }
}

親自試一試

相關頁面

教程:如何創建響應式頂部導航

教程:CSS 導航欄