LoginSignup
69
68

More than 5 years have passed since last update.

Bootstrapのレスポンシブなテーブルの列の幅を動的に変える

Last updated at Posted at 2015-05-13

やりたいこと

Bootstrapのレスポンシブ対応のテーブルで列の幅を自分が決めた幅で動的に変えたい!

bootstrapのバージョン: 3系
使うHTML

<div class="alt-table-responsive">
  <table class="table">
    <thead>
      <tr>
          <th>th1</th>
          <th>th2</th>
          <th>th3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
          <td>aaa</td>
          <td>bbb</td>
          <td>ccc</td>
      </tr>
      <tr>
          <td>ddd</td>
          <td>eee</td>
          <td>fff</td>
      </tr>
    </tbody>
  </table>
</div>

手順

①thタグにGrid systemのクラスを追加する
col-xs-3やcol-md-2のようなものですね。
これを付けることで、画面の大きさに合わせて列の幅が動的に変わります。

<th class="col-xs-3 col-ms-3 col-md-4 col-lg-4">th1</th>
<th class="col-xs-3 col-ms-3 col-md-3 col-lg-4">th2</th>
<th class="col-xs-1 col-ms-1 col-md-1 col-lg-1">th3</th>

これだけでも良いのですが、tableタグをtable-responsiveのクラスを付けたdivタグで囲んで画面の幅が小さい時にスクロールするテーブルにした際、テーブルの要素が長すぎるため折り返してほしいという場面があると思います。

②CSSを追加
折り返されない原因は、table-responsiveによって中のthタグとtdタグに「white-space: nowrap;」が指定されてしまうからだそうです。(参考:http://stackoverflow.com/questions/25916530/keep-column-width-using-responsive-table-bootstrap3)
なので、table-responsiveは使わずにCSSで

.alt-table-responsive {
    width: 100%;
    overflow-y: hidden;
    overflow-x: auto;
    -ms-overflow-style: -ms-autohiding-scrollbar;
    -webkit-overflow-scrolling: touch;
}

を指定すると、画面幅が小さい時に要素を折り返してくれるためスクロールする範囲を狭められます。

69
68
1

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
69
68