如何使用 CSS 在图像上添加导航菜单?


在网页上添加导航菜单并不是一项困难的任务。借助它,我们可以在图像上轻松添加导航菜单。首先,让我们为 HTML 文档的 body 设置 margin 和 padding。

设置文档 body 的样式

分别使用marginpadding属性为<body>元素设置 margin 和 padding。

body {
   margin:0px;
   margin-top:10px;
   padding: 0px;
}

菜单的位置

菜单放置在网页顶部的一些 margin 之后。此垂直顶部位置使用 margin-top 属性设置。

margin-top:10px;

为导航菜单设置一个 div

将<nav>放在<div>中。<nav>将使用<a>元素定义一组导航链接。链接放置在 href 属性中。

<div class="image-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>
</div>

使用 background 属性放置背景图像

background:url在网页上设置背景图像。background-size用于设置背景图像的大小。cover值表示将背景图像调整大小以覆盖整个容器。使用background-positon属性将图像放置在中心。

.image-nav{
   background:url('https://tutorialspoint.com/market/public/assets/images/business-top-banner.svg');
   min-height: 400px;
   padding: 20px;
   background-position: center;
   background-repeat: no-repeat;
   background-size: cover;
   width: 70%;
}

将导航菜单放置在图像上

overflow属性设置为auto,并将height属性设置为auto。<nav>元素现在将自动调整其高度以使其内容能够正确显示。

nav{
   width: 80%;
   background-color: rgb(23, 104, 43);
   overflow: auto;
   height: auto;
}

放置菜单链接

display属性设置为值inline-block。display 表示如何控制元素的布局。在这种情况下,display 属性的 inline-block 将元素显示为内联级块容器。

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

上面,为了从链接中删除下划线,将text-decoration设置为none

示例

以下是使用 CSS 在图像上添加导航菜单的代码:

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Document</title>
   <style>
      body{
         margin:0px;
         margin-top:10px;
         padding: 0px;
      }
      nav{
         width: 80%;
         background-color: rgb(23, 104, 43);
         overflow: auto;
         height: auto;
      }
      .links {
         display: inline-block;
         text-align: center;
         padding: 14px;
         color: rgb(255, 255, 255);
         text-decoration: none;
         font-size: 17px;
      }
      .links:hover {
         background-color: rgb(129, 123, 123);
      }
      .selected{
         background-color: rgb(0, 56, 42);
      }
      .image-nav{
         background:url('https://tutorialspoint.com/market/public/assets/images/business-top-banner.svg');
         min-height: 400px;
         padding: 20px;
         background-position: center;
         background-repeat: no-repeat;
         background-size: cover;
         width: 70%;
      }
   </style>
</head>
<body>
   <div class="image-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>
   </div>
</body>
</html>

更新于: 2023年11月15日

1K+ 浏览量

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.