如何使用 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; }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

设置菜单链接样式

要设置和显示菜单链接的样式,请将 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 生成底部带边框(下划线)导航链接的代码 -

Open Compiler
<!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+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告