如何使用 CSS 建立底部帶邊框(下劃線)的導航連結?


要建立帶下劃線的導航連結,請在 CSS 中使用 border-bottom 屬性。border-bottom 是底部邊框的寬度、樣式和顏色的簡寫形式。使用 :hover 選擇器,這些連結在懸停時也會顯示為帶下劃線。這樣,選定的連結也會帶下劃線。讓我們看看如何使用 HTML 和 CSS 在網頁上建立底部帶邊框,即帶下劃線的導航連結。

建立導航連結

使用 <nav> 元素在網頁上建立導航連結 -

<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 屬性設定為固定定位 -

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

設定菜單鏈接樣式

要設定和顯示菜單鏈接的樣式,請將 display 屬性設定為 inline-block。此外,將 tex-decoration 屬性設定為 none 以避免連結的預設下劃線 -

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

懸停連結

懸停連結屬性使用 :hover 選擇器設定。它使用 border-bottom 屬性帶下劃線 -

.links:hover {
   border-bottom: 2px solid purple;
}

選定連結

選定的連結預設為“首頁”。它使用 border-bottom 屬性帶下劃線 -

.selected{
   border-bottom: 2px solid purple;
}

示例

以下是使用 CSS 生成底部帶邊框(下劃線)導航連結的程式碼 -

<!DOCTYPE html>
<html lang="en">
<head>
   <title>HTML Document</title>
   <style>
      body{
         margin:0px;
         margin-top:60px;
         padding: 0px;
      }
      nav{
         position: fixed;
         top:0;
         width: 100%;
         background-color: rgb(251, 255, 196);
         overflow: auto;
         height: auto;
      }
      .links {
         display: inline-block;
         text-align: center;
         padding: 14px;
         color: rgb(0, 0, 0);
         text-decoration: none;
         font-size: 17px;
         font-weight: bolder;
      }
      .links:hover {
         border-bottom: 2px solid purple;
      }
      .selected{
         border-bottom: 2px solid purple;
      }
   </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>
   <h1>Hover on the above links</h1>
</body>
</html>

更新於: 2023-12-14

1K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告