こんな感じだった見た目を
この様にちょっと見やすくしたくて学んだことを備忘録として記載しています。
nth-childを使う。
nth-childはセレクタに追加して条件を指定する擬似クラスのひとつで、
子要素のn番目(nth)にスタイルを適用させることができます。
nth-childの書き方
要素:nth-child(値){スタイルの内容}
値には数字、2n+1などの式の他にeven(偶数)などを設定します。
例としては
- 偶数にのみ適用する場合:2nあるいはeven
- 奇数にのみ適用する場合:2n+1あるいはodd
- n番目に適用する場合:適用したい項目の順番の数値
- n番目以降すべてに適用する場合:n+適用を開始する項目の数値
「2n」とか懐かしい表記ですよね!
even(偶数)、odd(奇数)とか初めて知りましたよ・・・。
nth-last-childを使う。
nth-childがリストの上(最初)から数えるのに対し
nth-last-childはリストの最後から数えます。
stocks/index.html.erb
<table>
<thead>
<tr>
<th scope="col"><%= sort_order "display", "陳列" %></th>
<th scope="col"><%= sort_order "publisher", "出版社名" %></th>
<th scope="col"><%= sort_order "magazine_name", "雑誌名" %></th>
<th scope="col"><%= sort_order "num", "冊数" %></th>
<th scope="col"><%= sort_order "price", "本体価格" %></th>
<th scope="col"><%= sort_order "i_form", "発行形態" %></th>
<th scope="col"><%= sort_order "purchased", "買切雑誌" %></th>
</tr>
</thead>
<tbody>
<% @stocks.each do |stock| %>
<% if stock.num > 0 %>
<tr>
<td><%= stock.display %></td>
<td><%= stock.publisher %></td>
<td><%= stock.magazine_name %></td>
<td><%= stock.num %></td>
<td><%= stock.price.to_s(:delimited) %></td>
<td><%= stock.i_form %></td>
<td><%= stock.purchased %></td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
今回はこの様なリストを作成して
stock.css
.stock-page tbody tr:nth-child(2n){
background-color: #ddd;
}
.stock-page tbody tr:hover{
background-color: gray;
}
この様に指定してみました。
この指定の優れていると思ったことは
ソート機能にも対応してくれる
と、いうことだと思います。
当初、モデルデータのidが偶数の時に色を変える様に指定していたのですが
ソートをすると崩れてしまって逆に見づらくなってしまいました。
ウンウン唸っている時にこの擬似クラスを知る事ができてよかったです!
参考にさせていただいたサイト様
http://www.htmq.com/selector/nth-child.shtml
ありがとうございます!