如何使用 CSS 建立藥丸式導航選單?


藥丸式導航選單用於導航並增強使用者體驗。導航專案設定在其內。<nav> 元素用於建立選單,並且與藥丸式導航選單的工作方式相同。讓我們看看如何在網頁上建立藥丸式導航選單。

建立藥丸式導航選單

首先,我們將使用 <nav> 元素建立一個選單。連結使用 <a> 元素設定 -

<nav>
   <a class="links selected" href="#">Home</a>
   <a class="links" href="#">Login</a>
   <a class="links" href="#">Register</a>
   <a class="links" href="#">Contact Us</a>
   <a class="links" href="#">More Info</a>
</nav>

選單定位

選單使用 `overflow` 屬性(值為 `auto`)進行定位。高度也設定為 `auto` -

nav{
   width: 100%;
   background-color: rgb(255, 251, 251);
   overflow: auto;
   height: auto;
}

放置連結

使用 `display` 屬性將連結放置在選單中。`inline-block` 將水平設定連結。連結通常帶下劃線。為避免這種情況,請使用 `text-decoration` 屬性並將其設定為 `none` -

.links {
   display: inline-block;
   text-align: center;
   padding: 14px;
   text-decoration: none;
   font-size: 17px;
   border-radius: 5px;
   color:black;
}

滑鼠懸停連結

使用 `:hover` 選擇器設定懸停屬性。懸停時,背景顏色將更改 -

.links:hover {
   background-color: rgba(129, 129, 129, 0.473);
}

選定的連結

選中時,連結的背景色和文字顏色將更改 -

.selected{
   background-color: rgb(33, 126, 255);
   color: rgb(255, 255, 255);
}

示例

以下是使用 CSS 建立藥丸式導航選單的程式碼:

<!DOCTYPE html>
<html>
<head>
   <title>HTML Document</title>
   <style>
      nav{
         width: 100%;
         background-color: rgb(255, 251, 251);
         overflow: auto;
         height: auto;
      }
      .links {
         display: inline-block;
         text-align: center;
         padding: 14px;
         text-decoration: none;
         font-size: 17px;
         border-radius: 5px;
         color:black;
      }
      .links:hover {
         background-color: rgba(129, 129, 129, 0.473);
      }
      .selected{
         background-color: rgb(33, 126, 255);
         color: rgb(255, 255, 255);
      }
   </style>
</head>
<body>
   <h1>Pill navigation example</h1>
   <nav>
      <a class="links selected" href="#">Home</a>
      <a class="links" href="#">Login</a>
      <a class="links" href="#">Register</a>
      <a class="links" href="#">Contact Us</a>
      <a class="links" href="#">More Info</a>
   </nav>
</body>
</html>

更新於:2023年12月8日

832 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.