如何使用CSS建立垂直選單?


網頁上的垂直選單主要放置在左側或右側。這些左側或右側選單垂直排列,使使用者更容易瀏覽或點選它們。要建立垂直選單,請設定一個容器,並在其中設定菜單鏈接。display 屬性應設定為 block,以使選單垂直顯示。讓我們看看如何使用 HTML 和 CSS 建立垂直選單。

為選單設定容器

為選單設定一個 div。使用帶有 href 屬性的 <a> 元素新增菜單鏈接:

<div class="Menu">
   <a href="#" class="links selected">About Us</a>
   <a class="links" href="#">Social Links</a>
   <a class="links "href="#">Visit Us</a>
   <a class="links" href="#">More info</a>
   <a class="links" href="#">Phone Number</a>
</div>

設定選單的寬度

使用 width 屬性設定選單寬度:

.Menu {
   width: 200px;
}

垂直對齊選單

要垂直對齊選單,請使用值為 block 的 display 屬性。此外,要刪除菜單鏈接的下劃線,請將 text-decoration 屬性設定為 none:

.links {
   background-color: rgb(251, 255, 188);
   color: black;
   display: block;
   padding: 12px;
   text-decoration: none;
}

連結懸停顏色

當滑鼠游標懸停在菜單鏈接上時,顏色會發生變化。這使用 background-color 屬性設定:

.links:hover {
   background-color: rgb(85, 85, 85);
   color:white;
}

選定的連結

在選單上,選定的連結應始終具有不同的顏色。使用 background-color 屬性設定背景顏色:

.links.selected {
   background-color: rgb(0, 0, 0);
   color: white;
}

示例

以下是使用 CSS 生成垂直選單的程式碼:

<!DOCTYPE html>
<html>
<head>
   <style>
      .Menu {
         width: 200px;
      }
      .links {
         background-color: rgb(251, 255, 188);
         color: black;
         display: block;
         padding: 12px;
         text-decoration: none;
      }
      .links:hover {
         background-color: rgb(85, 85, 85);
         color:white;
      }
      .links.selected {
         background-color: rgb(0, 0, 0);
         color: white;
      }
   </style>
</head>
<body>
   <div class="Menu">
      <a href="#" class="links selected">About Us</a>
      <a class="links" href="#">Social Links</a>
      <a class="links "href="#">Visit Us</a>
      <a class="links" href="#">More info</a>
      <a class="links" href="#">Phone Number</a>
   </div>
</body>
</html>

更新於:2023年12月14日

891 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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