LoginSignup
9
6

More than 5 years have passed since last update.

data属性の値をcssのcontent:attrで入れてtableのレスポンシブをしてみた

Posted at

久々の投稿です。

data属性はいつもJSで操作するときにいじることが大半だったのですが、疑似要素を使って表現する方法があることを知りました。知らなかったのでメモTipsとして残しておきます。

さっそくやってみた。

完成したサンプルコードはこんな感じでやってみました。
http://codepen.io/redamoon/pen/ORyYQR

HTMLは以下のような構造で記述してみました。

<!-- contet:attr(data-title)を使ったサンプル -->
<table class="base-table">
  <thead>
    <tr>
      <th></th>
      <th>title1</th>
      <th>title2</th>
      <th>title3</th>
      <th>title4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>category01</th>
      <td data-title="title1">サンプルテキストサンプルテキストサンプルテキストサンプルテキスト</td>
      <td data-title="title2">サンプルテキストサンプルテキストサンプルテキストサンプルテキスト</td>
      <td data-title="title3">サンプルテキストサンプルテキストサンプルテキストサンプルテキスト</td>
      <td data-title="title4">サンプルテキストサンプルテキストサンプルテキストサンプルテキスト</td>
    </tr>
    <tr>
      <th>category02</th>
      <td data-title="title1">サンプルテキストサンプルテキストサンプルテキストサンプルテキスト</td>
      <td data-title="title2">サンプルテキストサンプルテキストサンプルテキストサンプルテキスト</td>
      <td data-title="title3">サンプルテキストサンプルテキストサンプルテキストサンプルテキスト</td>
      <td data-title="title4">サンプルテキストサンプルテキストサンプルテキストサンプルテキスト</td>
    </tr>
  </tbody>
</table>

サンプルのCSS(SCSS)になります。
メディアクエリを使っての切り替えで、767px以下のときにdata-titleをtbodyのtdに疑似要素:beforeにcontent attrで代入するようにしています。

*{
  margin:0;
  padding: 0;
}
.base-table{
  width: 100%;
  margin:0;
  th, td{
      padding: 10px;
  }
}
@media only screen and (min-width:767px) {
  .base-table{
    border-collapse: collapse;
    border: 1px solid #999;
    thead{
      th{
        background: #CCC;
        border: 1px solid #999;
      }
    }
    tbody{
      th{
        background: #47cf73;
        border: 1px solid #999;
      }
      td{
        border: 1px solid #999;
      }
    }
  }
}

@media only screen and (max-width:767px) {
  .base-table{
    box-sizing: border-box;
    thead{
      th{
        display: none;
      }
    }
    tbody{
      th{
        display: block;
        background: #47cf73;
        margin-bottom: 20px;
      }
      td{
        padding: 0 10px 10px;
        margin: 0;
        display: block;
        width: 100%;
        position: relative;
        box-sizing: border-box;
        &:before{
          background: #CCC;
          width: 100%;
          display: block;
          box-sizing: border-box;
          padding: 10px;
          margin-bottom: 10px;
          font-weight: bold;
          content: attr(data-title);
        }
      }
    }
  }
}

たまたま案件で見た参考サイトの表組みが、このようなattrを使った表現でレスポンシブをやっていたので試してみました。
attrは今後頻繁に使う可能性があると思ったので、今後のためのメモとして簡単なエントリーとしてまとめておきます。

タイムテーブルだったり大量のデータをテーブルで表現しているサイトなどをレスポンシブ化するときには便利な方法だと思いました。
※今回はtableで表現しましたが、違ったレイアウトパターンのときでも使えると思います。

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6