Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8825

【CSS】擬似クラス「nth-child」で学んだ事。

$
0
0

スクリーンショット 2020-12-13 18.27.43.png
こんな感じだった見た目を
スクリーンショット 2020-12-13 18.25.05.png
この様にちょっと見やすくしたくて学んだことを備忘録として記載しています。

nth-childを使う。

nth-childはセレクタに追加して条件を指定する擬似クラスのひとつで、
子要素のn番目(nth)にスタイルを適用させることができます。

nth-childの書き方

要素:nth-child(値){スタイルの内容}
値には数字、2n+1などの式の他にeven(偶数)などを設定します。
例としては

  • 偶数にのみ適用する場合:2nあるいはeven
  • 奇数にのみ適用する場合:2n+1あるいはodd
  • n番目に適用する場合:適用したい項目の順番の数値
  • n番目以降すべてに適用する場合:n+適用を開始する項目の数値

「2n」とか懐かしい表記ですよね!

nth-last-childを使う。

nth-childがリストの上(最初)から数えるのに対し
nth-last-childはリストの最後から数えます。

stocks/index.html.erb
<table><thead><tr><thscope="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-pagetbodytr:nth-child(2n){background-color: #ddd;}.stock-pagetbodytr:hover{background-color: gray;}

この様に指定してみました。
この指定の優れていると思ったことは
ソート機能にも対応してくれると、いうことだと思います。
当初、モデルデータのidが偶数の時に色を変える様に指定していたのですが
ソートをすると崩れてしまって逆に見づらくなってしまいました。
ウンウン唸っている時にこの擬似クラスを知る事ができてよかったです!

参考にさせていただいたサイト様

http://www.htmq.com/selector/nth-child.shtml
ありがとうございます!


Viewing all articles
Browse latest Browse all 8825

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>