如何用CSS建立響應式頭部?


在一個網頁上,首先可見的是頭部,然後是內容,最後是頁尾。頭部包含網站的logo和選單。它也可以在右側包含一個搜尋框。選單使用<nav>元素建立。選中的連結始終高亮顯示。懸停任何連結時,該特定連結的顏色都會改變。讓我們看看如何在網頁上使用CSS建立一個響應式頭部。

設定導航欄用於logo和選單

<nav>元素用於放置logo和選單。這兩者都使用<a>元素設定 -

<nav>
   <a class="links logo" href="#">Company Logo/Image</a>
   <div class="rightSection">
      <a class="selected links" href="h">Home</a>
      <a class="links" href="#">Contact Us</a>
      <a class="links" href="#">About Us</a>
      <a class="links" href="#">More Info</a>
      <a class="links" href="#">Register</a>
   </div>
</nav>

選單定位

要正確定位選單,請使用overflow屬性並將其設定為hidden -

nav {
   overflow: hidden;
   background-color: #330b7c;
   padding: 10px;
}

菜單鏈接定位

菜單鏈接位於<nav>的左側,使用float屬性,其值為left。要刪除連結的預設下劃線,請使用text-decoration屬性並將其設定為none -

.links {
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   font-weight: bold;
   float: left;
   color:white;
   text-align: center;
   padding: 12px;
   text-decoration: none;
   font-size: 18px;
   line-height: 25px;
   border-radius: 4px;
}

選中連結

選中的連結應該有不同的背景色和字型顏色 -

nav .selected {
   background-color: dodgerblue;
   color: white;
}

設定響應式

當網頁瀏覽器設定為小於870畫素時,響應式效果生效。display屬性設定為block值。float屬性設定為none -

@media screen and (max-width: 870px) {
   nav .links {
      float: none;
      display: block;
      text-align: left;
   }

示例

以下是使用CSS建立響應式頭部的程式碼:

<!DOCTYPE html>
<html>
<head>
   <style>
      * {box-sizing: border-box;}
      nav {
         overflow: hidden;
         background-color: #330b7c;
         padding: 10px;
      }
      .links {
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         font-weight: bold;
         float: left;
         color:white;
         text-align: center;
         padding: 12px;
         text-decoration: none;
         font-size: 18px;
         line-height: 25px;
         border-radius: 4px;
      }
      nav .logo {
         font-size: 25px;
         font-weight: bold;
      }
      nav .links:hover {
         background-color: rgb(214, 238, 77);
         color: rgb(42, 10, 94);
      }
      nav .selected {
         background-color: dodgerblue;
         color: white;
      }
      .rightSection {
         float: right;
      }
      @media screen and (max-width: 870px) {
         nav .links {
            float: none;
            display: block;
            text-align: left;
         }
         .rightSection {
            float: none;
         }
      }
   </style>
</head>
<body>
   <nav>
      <a class="links logo" href="#">Company Logo/Image</a>
      <div class="rightSection">
         <a class="selected links" href="h">Home</a>
         <a class="links" href="#">Contact Us</a>
         <a class="links" href="#">About Us</a>
         <a class="links" href="#">More Info</a>
         <a class="links" href="#">Register</a>
      </div>
   </nav>
</body>
</html>

更新於:2023年12月8日

4K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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