如何创建:响应式侧边栏
学习如何使用 CSS 创建响应式侧边导航菜单。
创建响应式侧边导航
第一步 - 添加 HTML:
<!-- 侧栏 --> <div class="sidebar"> <a class="active" href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <a href="#about">About</a> </div> <!-- Page content --> <div class="content"> .. </div>
第二步 - 添加 CSS:
/* 侧边导航菜单 */
.sidebar {
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
position: fixed;
height: 100%;
overflow: auto;
}
/* 侧栏链接 */
.sidebar a {
display: block;
color: black;
padding: 16px;
text-decoration: none;
}
/* 活动的/当前的链接 */
.sidebar a.active {
background-color: #04AA6D;
color: white;
}
/* 鼠标悬停时的链接样式 */
.sidebar a:hover:not(.active) {
background-color: #555;
color: white;
}
/* 页面内容。margin-left 属性的值应与侧边栏的 width 属性的值相匹配。 */
div.content {
margin-left: 200px;
padding: 1px 16px;
height: 1000px;
}
/* 在宽度小于 700 像素的屏幕上,将侧边栏变为顶部栏 */
@media screen and (max-width: 700px) {
.sidebar {
width: 100%;
height: auto;
position: relative;
}
.sidebar a {float: left;}
div.content {margin-left: 0;}
}
/* 在宽度小于 400 像素的屏幕上,将栏以垂直方式显示,而不是水平方式 */
@media screen and (max-width: 400px) {
.sidebar a {
text-align: center;
float: none;
}
}
相关页面
教程:CSS 导航栏