ul要素でディレクトリ構成をツリー状にスタイリングするCSS

ディレクトリ(ファイル)構成を示したいときに画像や<pre>
ではなく、<ul>
タグでスタイリングできるCSSを紹介します。
sponsored link
demo
デモはCodePenで確認できます。scssで書かれていますが、CodePenのサイトに飛び「View Compiled」ボタンをクリックするとCSSにコンパイル(変換)されたものが確認できます。
See the Pen tree menu by ManabuYasuda (@gaku) on CodePen.
参考にしたのはコリスさんのこちらの記事です。[CSS]多階層のリスト要素をツリー状にデザインするスタイルシートのテクニック | コリス
HTML
マークアップは<ul>
タグを入れ子にしたシンプルなものです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<ul class="tree-menu"> <li>stylesheet <ul> <li>Foundation <ul> <li>function</li> <li>variable</li> <li>mixin</li> <li>Vendor</li> <li>Vendor-extension</li> <li>Base</li> </ul> </li> <li>Layout</li> <li>Object <ul> <li>Component</li> <li>Project</li> <li>Utility</li> </ul> </li> </ul> </li> </ul> |
CSS
同じ値を繰り返し使用しているためSassの変数を定義しています。$tree-menu-padding
で余白の指定と、テキストとボーダーの縦位置を合わせるために使用しています。$tree-menu-border-width
でボーダーの幅を、$tree-menu-border-color
でボーダーの色を指定します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
$tree-menu-padding: 1.5em; // 行の高さを基準に余白と位置を揃える $tree-menu-border-width: 1px; $tree-menu-border-color: currentColor; // colorと同じ色を指定している .tree-menu { line-height: $tree-menu-padding; } .tree-menu, .tree-menu ul { margin: 0; padding: 0; list-style-type: none; } .tree-menu ul { position: relative; margin-top: ($tree-menu-padding / 2); margin-left: $tree-menu-padding; &:before { content: ""; display: block; position: absolute; top: 0; bottom: 0; left: 0; width: 0; border-left: $tree-menu-border-width solid $tree-menu-border-color; } } .tree-menu ul li { position: relative; margin: 0; padding: ($tree-menu-padding / 2) $tree-menu-padding; } .tree-menu ul li:before { content: ""; display: block; position: absolute; top: $tree-menu-padding; left: 0; width: ($tree-menu-padding / 2); height: 0; border-top: $tree-menu-border-width solid $tree-menu-border-color; } // 1.背景色を適宜変更してください。 // `inherit`(継承)はされず、`initial`(初期値)はtransparentです。 .tree-menu ul li:last-child:before { top: $tree-menu-padding; bottom: 0; height: auto; background-color: #eee; // [1] } |
いちばん最後の行でbackground-color: #eee;
を指定しています。これによってボーダーを一部隠しています。ですが、このプロパティは初期値がtransparent
で、さらに継承することができないので、直接背景色を指定する必要があります。