LoginSignup
2
2

More than 5 years have passed since last update.

RailsでBootstrapのグリッドシステムを使うときに、カラム数をRubyで計算する

Last updated at Posted at 2016-09-17

BootstrapのGridシステムについて

こちらのグリッドシステムが詳しいです
https://html5experts.jp/shumpei-shiraishi/1538/

本題

Gridシステムのcol-md-4とか3とか決めるの大変

<div class="container">
  <div class="row">
    <!--        ↓↓↓↓↓↓↓↓ これのことです -->
    <div class="col-md-4">レスポンシブに動く要素</div>
    <div class="col-md-4">レスポンシブに動く要素</div>
    <div class="col-md-4">レスポンシブに動く要素</div>
  </div>
</div>

【レスポンシブに動く要素】が増えたり減ったりする場合は、センスで決めるしかありません

Rubyで計算してみる

  # 要素数に対して適切なcol数を返す
  # @param [Integer] n 要素数
  # @param [Integer] min_col col数の最小値
  # @param [Integer] max_col col数の最大値
  # @return [Integer] 適切なcol数
  # @example
  #  - if n > 0
  #  - col_count = col_count(n, 2)
  #  - col_class = "col-sm-#{col_count}"
  def col_count(n = 1, min_col = 1, max_col = 12)
    return 12 if n <= 0
    ((n/(12/min_col).to_f).ceil*max_col)/n.to_f.ceil
  end

戻り値を一覧にしてみました

最小幅

要素数 カラム数
1 12
2 6
3 4
4 3
5 2
6 2
7 1
8 1
9 1

最小幅 2

要素数 カラム数
1 12
2 6
3 4
4 3
5 2
6 2
7 3
8 3
9 2

最小幅 3

要素数 カラム数
1 12
2 6
3 4
4 3
5 4
6 4
7 3
8 3
9 4

まとめ

動的に増減する要素を、いい感じにレイアウトできるようになったかもしれないです!
Ajaxで取得した動的コンテンツの再配置に使ってみたいと思います!

2
2
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
2
2