如何創建:響應式側邊欄

學習如何使用 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 導航欄