如何使用 CSS 建立“固定”選單?


要在網頁上建立固定選單,請使用position屬性並將值設定為fixed。使用width屬性將寬度設定為100%。

設定導航選單

使用<nav>元素在網頁上建立導航選單。連結使用<a>和href屬性設定 -

<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>

設定導航選單樣式

我們已使用position屬性(值為fixed)將選單定位為固定。使用width屬性將寬度設定為100% -

Nav {
   position: fixed;
   top: 0;
   width: 100%;
   background-color: rgb(39, 39, 39);
   overflow: auto;
   height: auto;
}

設定連結樣式

菜單鏈接的display屬性設定為inline-block值。display屬性指示如何控制元素的佈局。在本例中,display屬性的inline-block值將元素顯示為內聯級塊容器。文字裝飾設定為none -

.links {
   display: inline-block;
   text-align: center;
   padding: 14px;
   color: rgb(178, 137, 253);
   text-decoration: none;
   font-size: 17px;
}

懸停效果

使用:hover選擇器更改連結在懸停時的背景顏色 -

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

選中連結

更改選中連結的背景顏色 -

.selected{
   background-color: rgb(0, 18, 43);
}

示例

以下是使用 CSS 生成固定選單的程式碼 -

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Document</title>
   <style>
      body{
         margin:0px;
        margin-top:60px;
         padding: 0px;
      }
      nav{
         position: fixed;
         top: 0;
         width: 100%;
         background-color: rgb(39, 39, 39);
         overflow: auto;
         height: auto;
      }
      .links {
         display: inline-block;
         text-align: center;
         padding: 14px;
         color: rgb(178, 137, 253);
         text-decoration: none;
         font-size: 17px;
      }
      .links:hover {
         background-color: rgb(100, 100, 100);
      }
      .selected{
         background-color: rgb(0, 18, 43);
      }
   </style>
</head>
<body>
   <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>
   <div class="sample-content">
      <h1>Here are some headers</h1>
      <h2>Here are some headers</h2>
      <h3>Here are some headers</h3>
      <h4>Here are some headers</h4>
      <h1>Here are some headers</h1>
      <h2>Here are some headers</h2>
      <h3>Here are some headers</h3>
      <h4>Here are some headers</h4>
   </div>
</body>
</html>

更新於: 2023-11-17

603 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告