リストタグでレスポンシブなカラムを作る
レスポンシブウェブデザインで、あるブロックをPC&Tablettなら2カラムや3カラム、スマホなら1カラムにするということがよくありますが、column-count を使うと幅を自動で決めてくれるのでとても便利です。
リストタグで作る場合はこんな感じになります。
- リスト1つ目
- リスト2つ目
- リスト3つ目
分割をコントロールする
この時、リストの内容にバラツキがあると、下の例のように予期せぬところでボックスが分割されてしまうことがあります。
- リスト1つ目
- リスト2つ目:Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
- リスト3つ目
これを回避するには、break-inside: avoid; を指定します。
リストタグで作る場合は、<ul> に column-count を指定し、<li> に break-inside: avoid; を指定します。
以下が指定した例です。
- リスト1つ目
- リスト2つ目:Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
- リスト3つ目:Lorem Ipsum is simply dummy text of the printing and typesetting industry.
HTML&CSS
これのHTMLとCSSはこんな感じです。
HTML
<ul class="three-column"> <li>リスト1つ目</li> <li>リスト2つ目</li> <li>リスト3つ目</li> </ul>
CSS
.three-column {
list-style: none;
column-count: 1;/*スマホの時は1カラム*/
padding: 1rem 0;
}
@media screen and (min-width:768px) {/*PC&Tablettの時*/
.three-column {
column-count: 3;/*3カラム*/
}
.three-column li {
display: inline-block;
break-inside: avoid;
}
}
SASS(SCSS)でもっと便利に
Sassで書くともっと使いやすくなります。
// カラム分割
@mixin column-set($column-count:3){
list-style: none;
column-count: 1;
padding: 1rem 0;
@include pc{
column-count: $column-count;
li{
display: inline-block;
break-inside: avoid;
}
}
}
// 2カラム
.two-column{
@include column-set(2);
}
// 3カラム
.three-column{
@include column-set;
}カラムの数は適宜変えられるように引数にしているので、とっても便利。
尚、@include pc は以下のように指定してあります。私はタブレットとPCは同じ画面で良いと思っているので、基本的にはひとまとめにしています。
$pc: 768px; // タブレット・PC
@mixin pc {
@media (min-width: ($pc)) {
@content;
}
}
以上です。
誰かの役に立つかな?
