Result
※内容は最新の方法的なものではなく以前からよく使われている方法です
個人的に毎回悩むtableのRWD対応ですが、やはり少ないコードで実装できるのが理想だと思うのでいろいろ記事を参考にしながら再考してみました
なるべく少ないコードでレスポンシブなtable、というタイトルではありますが、そもそもtableの内容によって最適解は異なるので答えを出すのは難しそうですね
css
table { border-collapse : collapse ; text-align : left ; width : 100% ; } table tr { border-bottom : 1px solid } table th, table td { padding : 10px 20px ; } table td:before { /*モバイル用の見出し。PC向けでは非表示にする*/ background : #eee ; color : dimgrey; display : none ; font-size : 10px ; font-weight : bold ; padding : 5px ; position : absolute ; text-transform : uppercase ; top : 0 ; left : 0 ; } /* モバイル向け */ @media( max-width : 800px ) { table thead { /*非表示にする*/ left : -9999px ; position : absolute ; visibility : hidden ; } table tr { /*flexboxで並べる*/ border-bottom : 0 ; display : flex ; flex-direction : row ; flex-wrap : wrap ; margin-bottom : 40px ; } table td { /*ここでは2ペインとします*/ border : 1px solid ; margin : 0 -1px -1px 0 ; padding-top : 35px ; position : relative ; width : 50% ; } table td:before { /*モバイル用の見出しを表示*/ display : block ; } /*見出し*/ td:nth-of-type( 1 ):before { content : "高知" ; } td:nth-of-type( 2 ):before { content : "東京" ; } td:nth-of-type( 3 ):before { content : "宮崎" ; } td:nth-of-type( 4 ):before { content : "沖縄" ; } td:nth-of-type( 5 ):before { content : "岩手" ; } td:nth-of-type( 6 ):before { content : "北海道" ; } } |
PCサイトでは普通に実装、スマホ等ではflexboxでレイアウトを作り、thead要素を非表示にし、代替として疑似要素で見出しを表示します
html
< table > < thead > < tr > < th >高知</ th > < th >東京</ th > < th >宮崎</ th > < th >沖縄</ th > < th >岩手</ th > < th >北海道</ th > </ tr > </ thead > < tbody > < tr > < td >500</ td > < td >450</ td > < td >680</ td > < td >430</ td > < td >600</ td > < td >620</ td > </ tr > < tr > < td >1523</ td > < td >2536</ td > < td >6632</ td > < td >8965</ td > < td >4100</ td > < td >2132</ td > </ tr > </ tbody > </ table > |
HTMLは綺麗なままで済むのが利点です