Quantcast
Channel: Staff BLOG –ホームページ制作やリニューアル制作と印刷物デザインのWPC大阪
Viewing all articles
Browse latest Browse all 22

テーブルレイアウトを、スマートフォンにレスポンシブ対応させるCSS

$
0
0

スマホ対応が当たり前になってきたので、昔作ったサイトの会社概要とかフォームのテーブルデザインを、できるだけ簡単にレスポンシブ対応させたいものです。
CSSを追記するだけでイケる場合も多いので、コピペ用に書いておきます。

table1

capture

デモページ DEMO

まず、一番オーソドックスな左見出しのテーブルの場合です。

HTML 左見出し一例

<table>
<tr>
<th>見出し1</th><td>値1</td>
</tr>
<tr>
<th>見出し2</th><td>値2</td>
</tr>
<tr>
<th>見出し3</th><td>値3</td>
</tr>
</table>

このtableタグに「class="table-sp"」というクラスを付けます。
(全てのtableに効かせるなら上記は要りません。)

<table class="table-sp">

こうですね。

で、下記のCSSを追記します。

CSS 左見出し一例

@media screen and (max-width: 768px) {
	.table-sp,
	.table-sp tbody,
	.table-sp thead,
	.table-sp tr,
	.table-sp td,
	.table-sp th {display:block;}

	.table-sp th {width:auto;}
}

以上で768px以下なら縦に並びます。
DEMOページでサンプル見れますー

で、上に見出しが並んでる時はと言いますと、
「thead」と「tbody」がなければ追記してください。

HTML 上見出し一例

<table class="table-sp2">
<thead>
<tr>
<th>&nbsp;</th>
<th>見出し1</th>
<th>見出し2</th>
<th>見出し3</th>
</tr>
</thead>
<tbody>
<tr>
<td>区分1</td>
<td>値1</td>
<td>値2</td>
<td>値3</td>
</tr>
</tbody>
</table>

テーブルにクラスを付けるのをお忘れなく。

後はCSSに下記を付け足してください。

CSS 上見出し一例

@media screen and (max-width: 768px) {
	.table-sp2,
	.table-sp2 tbody,
	.table-sp2 thead,
	.table-sp2 td,
	.table-sp2 th {display:block;}

    .table-sp2 {  
		border:none;
        margin: 0 auto;
		width: 90%;
    }
    .table-sp2 thead{  
        float: left;
    }
    .table-sp2 tbody{ 
        overflow-x: auto; 
        white-space: nowrap;
		width: auto;
    }
    .table-sp2 th{ 
        width:auto;
    }
    .table-sp2 tbody tr{ 
        display: inline-block; 
        margin: 0 -3px;
    }
}

改行すると崩れちゃうので「white-space: nowrap;」と、
横にはみ出た場合用に「overflow-x: auto;」を付けています。
ただ、全てに対応できるかわかりませんので、適宜変更修正は必要かもです・・・
参考にはなるかと思いますので、ゴニョゴニョしてみてくださいー


Viewing all articles
Browse latest Browse all 22

Trending Articles