列を作成するとき、通常、特別なCSSクラスを最初と最後の要素に適用する必要があります。 この記事では、列のレイアウトを単純化し、適応性を高める小さなトリックについて説明します。
このメソッドの本質は、
nth-of-type疑似
クラスを使用することです。異なるサイズの画面で列の数と幅が変化します(
Demo )。
最初と最後の要素にクラスを使用することの欠点
正しく表示するために各行の列に.firstクラスと.lastクラスを適用するのは非常に面倒であり、適応レイアウトの問題もあります。

nth-of-typeを使用する
式:nth-of-type(An + B)は、要素の浮動小数点数とパディングを非常に簡単にクリアするのに役立ちます。例えば:
- .grid4 .col:nth-of-type(4n + 1) -4番目ごとの.col要素は新しい行で始まります
- .grid2 .col:nth-of-type(2n + 1) -1秒ごとに.col要素が新しい行で始まります

.grid4 .col:nth-of-type(4n+1), .grid3 .col:nth-of-type(3n+1), .grid2 .col:nth-of-type(2n+1) { margin-left: 0; clear: left; }
適応性
ページがレスポンシブになるために、メディアクエリを使用し、すべての値をパーセンテージで示します。
.col { background: #eee; float: left; margin-left: 3.2%; margin-bottom: 30px; } .grid4 .col { width: 22.6%; } .grid3 .col { width: 31.2%; } .grid2 .col { width: 48.4%; }
ウィンドウのサイズを変更するときに(740ピクセル未満)、4列から3列のグリッドに移行する方法を次に示します。
- .Grid4 .colは、幅が31.2%(ウィンドウ全体の幅の3分の1)未満になると変化します
- 左インデントのリセット
- nth-of-type(3n + 1)で左パディングをオーバーライドして、3列のグリッドを作成します

@media screen and (max-width: 740px) { .grid4 .col { width: 31.2%; } .grid4 .col:nth-of-type(4n+1) { margin-left: 3.2%; clear: none; } .grid4 .col:nth-of-type(3n+1) { margin-left: 0; clear: left; } }
ウィンドウ幅が600px未満の場合、4列および3列から2列グリッドへの移行が発生します。
@media screen and (max-width: 600px) { .grid4 .col { width: 48.4%; } .grid4 .col:nth-of-type(3n+1) { margin-left: 3.2%; clear: none; } .grid4 .col:nth-of-type(2n+1) { margin-left: 0; clear: left; } .grid3 .col { width: 48.4%; } .grid3 .col:nth-of-type(3n+1) { margin-left: 3.2%; clear: none; } .grid3 .col:nth-of-type(2n+1) { margin-left: 0; clear: left; } }
幅全体を拡大するには、次のコードを使用します。
@media screen and (max-width: 400px) { .col { width: 100% !important; margin-left: 0 !important; clear: none !important; } }
Internet Explorerで作業する
Internet Explorerバージョン8以前では、メディアクエリとnth-of-typeはサポートされていません。 この問題を解決するには、
selectivizr.js (nth-of-typeを修正)および
respond.js (メディアクエリを修正)を使用できます。 残念ながら、selectivizr.jsとrespond.jsは一緒にはうまく機能しません。nth-of-typeはメディアクエリ内では機能しません。