LoginSignup
3
3

More than 5 years have passed since last update.

擬似クラス カラムレイアウトでの便利な使用方法

Last updated at Posted at 2017-10-20

擬似クラスによるカラムレイアウト

フロントエンド開発をしていると必ずカラムレイアウトが登場します。
(正確には、グリッドレイアウトを用いたグリッドシステム、グリッドデザインと呼ぶ)

そのカラムに対して、まるでテーブルレイアウトのようにborderを適用するが、擬似クラスを用いるとプロパティの打ち消しを全くすることなく実現できるので、備忘録がてら投稿致します。

※擬似クラス(nth-child, nth-of-type)の詳細に関しては、擬似クラス nth-childとnth-of-typeをご確認ください。
※より実践的な留意点に関しては、擬似クラス カラムレイアウトでの留意点をご確認ください。

単純なカラムレイアウト

image.png

.item {  /* 1〜9 */
  border-top: 1px solid gray;
  border-left: 1px solid gray;
}
.item:nth-child(3n) {  /* 3, 6, 9 */
  border-right: 1px solid gray;
}
.item:nth-last-child(-n+3){  /* 7〜9 */
  border-bottom: 1px solid gray;
}

 上ボーダーのいらないカラムレイアウト

image.png

.item {  /* 1 〜 9  */
  border-left: 1px solid gray;
  border-bottom: 1px solid gray;
}
.item:nth-child(3n) {  /* 3, 6, 9 */
  border-right: 1px solid gray;
}

下ボーダーのいらないカラムレイアウトは、.itemのborder-bottomをborder-topに変更するだけで可能。

上下ボーダーのいらないカラムレイアウト

image.png

.item {  /* 1〜9 */
  border-left: 1px solid gray;
}
.item:nth-child(3n) {  /* 3, 6, 9 */
  border-right: 1px solid gray;
}
.item:not(:nth-last-child(-n+3)){  /* 1〜6 */
  border-bottom: 1px solid gray;
}

上下にコンテンツがあるかbox-shadowがかかっている場合に必要になる。

上下左右ボーダーのいらないカラムレイアウト

image.png

.item:not(:nth-child(3n)) {  /* 1, 2, 4, 5, 7, 8 */
  border-right: 1px solid gray;
}
.item:not(:nth-last-child(-n+3)) {  /* 1〜6 */
  border-bottom: 1px solid gray;
}

BEMで言う、別のBlock内に内包されている場合など需要がある。
右の1列だけborder-rightがいらない。:not(:nth-child(3n))
下の1行だけborder-bottomがいらない。:not(:nth-last-child(-n+3))

お気づきだとは思いますが、行数をいくら増やしても同じ結果が得られるようになっています。
また、今回は、どれも3カラムだが、4カラムでも擬似クラスの中の 34 にするだけで同様の動作ができる。

使用した便利な擬似クラス

nth-last-child

  • nth-last-child(n): 最後からn番目に適用される
  • nth-last-child(-n+3): 最後から3番目まで適用される

nth-first-child(-n+3)も同様で、最初から3番目まで適用される。

メリット

  • プロパティの上書き回数を少なく、感覚的にレイアウトを実装することができる。

これらを使いこなせると他にも様々な応用ができると考えられる。

not

  • li:not(.item) //itemクラスでないliタグに適用される
  • .item:nth-child(3n):not(:nth-last-child(-n+3)) //最後から3番目までじゃない、かつ、3の倍数の要素がitemクラスなら適用

注意点

  • 上記のようにセレクタに連結して条件を増やすことができるが、連結しただけ詳細度が上昇する

※正確には、

否定擬似クラスの :not は詳細度の計算では擬似クラスとは見なされません。しかし、否定擬似クラスの中に置かれたセレクタは、通常のセレクタのように計算されます。
引用:MDN

参考

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3