如何使用 CSS 在影像上新增導航選單?
在網頁上新增導航選單並不是一項困難的任務。藉助它,我們可以在影像上輕鬆新增導航選單。首先,讓我們為 HTML 文件的 body 設定 margin 和 padding。
設定文件 body 的樣式
分別使用margin和padding屬性為<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.tw/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.tw/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>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP