/* 定义一级菜单样式 */ #nav { width: 200px; height: auto; background-color: #F8F8F8; border: 1px solid #E5E5E5; padding: 10px; } #nav ul { margin: 0; padding: 0; list-style: none; } #nav ul li { margin: 0; padding: 0; } #nav ul li a { display: block; padding: 10px; font-size: 16px; color: #333; text-decoration: none; border-bottom: 1px solid #E5E5E5; } #nav ul li a:hover { background-color: #FFF; color: #000; } /* 定义二级菜单样式 */ #nav ul ul { display: none; } #nav ul li:hover >ul { display: inherit; } #nav ul ul li { position: relative; } #nav ul ul ul { position: absolute; top: 0; left: 100%; } #nav ul ul li a { padding: 5px 10px; font-size: 14px; color: #333; background-color: #F8F8F8; border-bottom: none; } #nav ul ul li a:hover { background-color: #E5E5E5; color: #000; }
以上代码中,大家定义了左侧导航栏的外层容器为id为nav的一个div元素。在这个容器中,大家设置了一级菜单的样式,其中用了ul和li标签来组织菜单,用a标签来定义菜单项的样式。
为了实现二级菜单显示与隐藏的效果,大家使用了CSS中的:hover选择器来控制二级菜单是否显示。在CSS中,大家首先隐藏了二级菜单#nav ul ul的显示,当一级菜单#nav ul li:hover时,通过显示inherit属性来显示ul下的ul元素,即二级菜单。
二级菜单的a标签样式与一级菜单类似,但在位置和样式上进行了修改,使得二级菜单显示在一级菜单下方,且以灰色背景和更小的字体进行区分。
这便是一个基于CSS样式的简单二级菜单左侧导航栏的实现。通过对样式的调整,还可以实现更复杂的导航设计,让网页更加美观、实用。