tableで横スクロールできるようにする

スマホサイトなどでたまに見かける、コンテンツ幅からはみ出たtableを横スクロールさせる処理を実装してみます。

サンプルコード

横長のtableを用意します。

<div class="table-scroll">
	<table>
		<tr>
			<th>名前</th>
			<th>よみ</th>
			<th>誕生日</th>
			<th>身長</th>
			<th>血液型</th>
			<th>CV</th>
		</tr>
		<tr>
			<td>星野 みやこ</td>
			<td>ほしの みやこ</td>
			<td>9月9日</td>
			<td>163cm</td>
			<td>A</td>
			<td>上田麗奈</td>
		</tr>
		〜 略 〜
	</table>
</div>

tableの親要素の.table-scrollがスクロールする要素になります。

次にCSSですが、.table-scrollにスクロールと合わせてwhite-space: nowrap;を設定してtableがコンテンツ幅をはみ出すようにします。

.table-scroll {
	overflow-x: auto;
	white-space: nowrap;
	-webkit-overflow-scrolling: touch;
}
table {
	width: 100%;
}

これでブラウザ幅が狭い時に横スクロールバーが出るようになりました。
tableを横スクロールさせるデモページ1

table内のテキストが短い場合は問題ないのですが、少し長めのテキストが入ったりした場合に意図した形にならないことがありました。

<div class="table-scroll">
	<table>
		<tr>
			<th>名前</th>
			<th>よみ</th>
			<th>誕生日</th>
			<th>身長</th>
			<th>血液型</th>
			<th>説明</th>
			<th>CV</th>
		</tr>
		<tr>
			<td>星野 みやこ</td>
			<td>ほしの みやこ</td>
			<td>9月9日</td>
			<td>163cm</td>
			<td>A</td>
			<td>コスプレ衣装作りが趣味のコミュ障女子大生。</td>
			<td>上田麗奈</td>
		</tr>
		〜 略 〜
	</table>
</div>

white-space: nowrap;を設定しているので、テキストが長い場合でも自動で改行されなくなっています。
tableを横スクロールさせるデモページ2

別の方法として、tableに最小幅を指定することでも対応できます。

.table-scroll {
	overflow-x: auto;
	-webkit-overflow-scrolling: touch;
}
table {
	width: 100%;
	min-width: 750px;
}

これでテキストが長い場合でも一定位置で自動改行されるようになりました。
tableを横スクロールさせるデモページ3

先ほどの例だと幅のバランスが悪いので、列ごとに幅を設定します。

<div class="table-scroll">
	<table>
		<tr>
			<th class="name">名前</th>
			<th class="name">よみ</th>
			<th class="birthday">誕生日</th>
			<th class="height">身長</th>
			<th class="blood-type">血液型</th>
			<th class="description">説明</th>
			<th class="cv">CV</th>
		</tr>
		<tr>
			<td>星野 みやこ</td>
			<td>ほしの みやこ</td>
			<td>9月9日</td>
			<td>163cm</td>
			<td>A</td>
			<td>コスプレ衣装作りが趣味のコミュ障女子大生。</td>
			<td>上田麗奈</td>
		</tr>
		〜 略 〜
	</table>
</div>
.table-scroll {
	overflow-x: auto;
	-webkit-overflow-scrolling: touch;
}
table {
	width: 100%;
	min-width: 750px;
}
.name {
	width: 15%;
}
.birthday {
	width: 10%;
}
.height {
	width: 10%;
}
.blood-type {
	width: 10%;
}
.description {
	width: 25%;
}
.cv {
	width: 15%;
}

tableを横スクロールさせるデモページ4
 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930