可折り畳みのサイドバーの作成方法

折り畳み可能なサイドバーメニューの作成方法を学びます。

ボタンをクリックして折り畳み可能なサイドバーを開く:

実際に試してみる:

折り畳み可能なサイドバーを作成する

第1段 - HTMLを追加:

<div id="mySidebar" class="sidebar">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>
</div>
<div id="main">
  <button class="openbtn" onclick="openNav()">☰ サイドバーを開く</button>
  <h2>折り畳み可能なサイドバー</h2>
  <p>Content...</p>
</div>

第2段 - CSSを追加:

/* サイドバーのメニュー */
.sidebar {
  height: 100%; /* 100% 全高 */
  width: 0; /* 0 width - JavaScriptを使用してこの設定を変更します */
  position: fixed; /* 元の位置に保つ */
  z-index: 1; /* 顶部に保つ */
  top: 0;
  left: 0;
  background-color: #111; /* 黒色 */
  overflow-x: hidden; /* 水平スクロールを無効にします */
  padding-top: 60px; /* コンテンツを上から60pxの位置に配置 */
  transition: 0.5s; /* 0.5 秒のトランジション効果でサイドバーをスライド */
}
/* サイドバーのリンク */
.sidebar a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}
マウスをナビゲーションリンクに重ね合わせると、色を変更します。
.sidebar a:hover {
  color: #f1f1f1;
}
/* 閉じるボタンの位置とスタイル(右上角) */
.sidebar .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}
/* 侧边栏を開くためのボタン */
.openbtn {
  font-size: 20px;
  cursor: pointer;
  background-color: #111;
  color: white;
  padding: 10px 15px;
  border: none;
}
.openbtn:hover {
  background-color: #444;
}
/* ページコンテンツのスタイルを設定 - 侧边导航を開く際にページコンテンツを右に動かす場合は、このスタイルを使用します */
#main {
  transition: margin-left .5s; /* 渡過効果を希望する場合 */
  padding: 20px;
}
/* 高さが450ピクセル以下の小さいスクリーン上では、側边栏のスタイルを変更します(内側マージンとフォントサイズを減らします) */
@media screen and (max-height: 450px) {
  .sidebar {padding-top: 15px;}
  .sidebar a {font-size: 18px;}
}

第3ステップ - JavaScriptを追加:

/* 侧边栏の幅を250pxに設定し、ページコンテンツの左外側マージンを250pxに設定します */
function openNav() {
  document.getElementById("mySidebar").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
}
/* 侧边栏の幅を0に設定し、ページコンテンツの左外側マージンを0に設定します */
function closeNav() {
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft = "0";
}

実際に試してみる:

関連ページ:

チュートリアル:CSSナビゲーションバー: