CSS Grid Layout は、HTML 要素をタイル状に自由に配置することができるレイアウト手法です。ページを複数のカラムに分割したり、カードを整然と並べたりといったレイアウトを、数行の CSS で作ることができます。
Can I use を見ると、IE 10 から対応はしているのですが、古い構文しか使えません。Autoprefixer を使うと、新しい構文で書かれたグリッドレイアウトの一部を、IE でも表示できるようにしてくれます。
Autoprefixer の設定
ここでは Laravel Mix を使って設定します。前の記事で Mix を単体で使う方法を紹介しているので、まだ環境がない方はそちらを読んでいただければと思います。
デフォルトでは前述のグリッドを IE でシミュレートする機能はオフになっているので、設定を変更します。webpack.mix.js に .options を追加します。
mix
.sass('resources/sass/app.scss', 'public/css')
.options({
postCss: [
require('autoprefixer')({
grid: 'autoplace',
})
],
})
これだけで設定は終了です。早速グリッドレイアウトを使ってみましょう。
※ちなみに、他の設定と組み合わせる場合は以下のようになります。
mix.options({
postCss: [
require('autoprefixer')({
grid: 'autoplace',
})
],
processCssUrls: false,
})
グリッドレイアウトを使う
ここでは、Autoprefixer が処理できる範囲でのグリッドレイアウトを紹介します。
このグリッドレイアウトには、行数と列数を決めて子要素をタイル状に並べる自動配置と、テンプレートを作って手動で子要素の場所を決める手動配置があります。
グリッドレイアウトを作るための HTML は非常にシンプルで、グリッドコンテナーと呼ばれる親要素の中に、グリッド配置する子要素を入れるだけです。コンテナー直下の要素は、自動的にグリッドアイテムとなります。
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
</div>
CSS の指定は、どちらの配置を使うかによって異なります。まずは簡単な自動配置グリッドを作ってみましょう。