如何使用 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 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.