レスポンシブのコーディングにこそSASS
sassでコーディングを始めてかれこれ1年以上たちます。僕の中でsassを定着させたのはレスポンシブデザインのコーディングのときです。 むしろレスポンシブでコーディングするときこそsassは大活躍します!とちょっとテンション高めですが、気にしないで下さい。
メディアクエリをつかったレスポンシブのコーディングではブレイクポイントと呼ばれるレイアウトの分岐ポイントがあります。 通常は
1 2 3 4 5 6 7 8 9 10 11 |
ブレイクポイント(スマートフォン){ スタイルを記述 } ブレイクポイント(タブレット){ スタイルを記述 } ブレイクポイント(PC){ スタイルを記述 } |
のような感じの記述になり同じセレクタでスタイルが違うと3箇所に記述しなくてはなりません。最初のうちはコードが少ないので3箇所に記述するのもそれほど億劫にはならないかもしれませんが記述が増えれば増える程面倒な作業になってきます。
sassではセレクタの記述をコンパイル時にブレイクポイント毎に分散させることができます。
バシャログさんの【Sass】Sassでレスポンシブ!メディアクエリを便利に書こう。
でその方法が紹介されていました。
これは目から鱗でした!記事のタイトル通り便利にメディアクエリが便利に書けます。便利にメディアクエリが書けすぎます!
ブレイクポイントを「styles.scss」にスタイルを「_media-query.scss」に記述します。_を付け忘れててもコンパイルは通りますがエラーだらけのmedia-query.cssが生成されますので_を付け忘れないで下さい。
styles.scss
styles.scssにはブレイクポイントを記述します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@charset "UTF-8"; $type: common phone tablet screen; $type: common; @import "media-query"; @media only screen and (max-width:399px) { $type: phone; @import "media-query" } @media only screen and (min-width:400px) and (max-width:979px) { $type: tablet; @import "media-query" } @media only screen and (min-width:980px) { $type: screen; @import "media-query" } |
_media-query.scss
_media-query.scssにスタイルを記述します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
.header{ @if $type == common { @include c_o; overflow:hidden; background:$sub_color;} @if $type == phone { display:none;} nav{ @if $type == tablet{ width:100%;} @if $type == screen{ @include screen_inner; height:50px; line-height:0;} ul{ li{ @if $type == common { display:inline-block; float:left;} @if $type == tablet{ width:15%;} @if $type == screen{ background:#fff;} } li:nth-of-type(6){ @if $type == tablet{ width:25%;} } } } } |
styles.css
コンパイルされたstyles.cssの内容です。
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 |
@charset "UTF-8"; .header { width: 100%; text-align: center; overflow: hidden; background: #3a3a3a; } .header nav ul li { display: inline-block; float: left; } @media only screen and (max-width: 399px) { .header { display: none; } } @media only screen and (min-width: 400px) and (max-width: 979px) { .header nav { width: 100%; } .header nav ul li { width: 15%; } .header nav ul li:nth-of-type(6) { width: 25%; } } @media only screen and (min-width: 980px) { .header nav { width: 980px; margin: 0 auto; height: 50px; line-height: 0; } .header nav ul li { background: #fff; } } |
ブレイクポイント毎に分散してコンパイルしてくれると記述がやっぱり楽になりますし、前後のつながりも把握しやすいです。結果統一性のあるCSSがかけることにもつながるのかなぁと思います。 これができるって言うだけでsassでコーディングする意味があります!
- 2013年11月07日木曜日
- :Naruhiko Wakai
comments