CSS 垂直导航栏
垂直导航栏
要构建一个垂直导航栏,除了上一页的代码之外,您还可以对列表中的 <a> 元素进行样式设置。
示例说明
display: block;
- 将链接显示为块级元素,使整个链接区域(而不仅仅是文本)可点击,并允许我们指定宽度(以及可选的内边距、外边距、高度等)。width: 60px;
- 默认情况下,块级元素会占据可用宽度的全部。我们希望将其指定为 60 像素的宽度。
您也可以设置 <ul> 的宽度,并移除 <a> 的宽度,因为当它们显示为块级元素时,它们将占据可用宽度的全部。这将产生与我们之前的示例相同的结果。
示例
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 60px;
}
li a {
display: block;
}
自己动手试一试 »
垂直导航栏示例
创建具有灰色背景色的基本垂直导航栏,并在用户鼠标悬停在链接上时更改背景色。
示例
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
}
li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}
/* 鼠标悬停时更改链接颜色 */
li a:hover {
background-color: #555;
color: white;
}
自己动手试一试 »
活动/当前导航链接
为当前链接添加“active”类,以告知用户他/她当前在哪个页面。
居中文本并添加边框
添加 text-align:center
到 <li> 或 <a> 以居中文本。
为 <ul> 添加 border
属性,在导航栏周围添加边框。如果您还希望导航栏内部有边框,请为除最后一个元素外的所有 <li> 元素添加 border-bottom
。
示例
ul {
border: 1px solid #555;
}
li {
text-align: center;
border-bottom: 1px solid #555;
}
li:last-child {
border-bottom: none;
}
自己动手试一试 »
全高固定垂直导航栏
创建全高、"粘性"的侧边导航。
示例
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 25%;
background-color: #f1f1f1;
height: 100%; /* 全高度 */
position: fixed; /* 使其固定,即使滚动 */
overflow: auto; /* 如果侧边导航内容过多,则启用滚动 */
}
自己动手试一试 »
注意:此示例在移动设备上可能无法正常工作。