cssの「~」を用いたロジックについて

理解したいこと

以下に示すHTMLとCSSを用いて星マークを用いたレビュー機能の動作を実現したのですが、CSSの.star-rating input:checked ~ label の意味がいまいち理解できません。

画像のfill_star.pngは星マークの画像で、no_fill_star.pngは中身が空白の星マークの画像です。

なぜ星マークをクリックすることでその星マークと左側の星マークがfill_starになり、右側の星マークはno_fill_starにするという動作が実現できているのでしょうか。

どなたかご説明していただける方はいらっしゃっればよろしくお願いします。

該当のソースコード

HTML

1<div class="star-rating"> 2 <input type="radio" name="rating" value="0" id="star0" checked> 3 <label for="star1"></label> 4 <input type="radio" name="rating" value="1" id="star1"> 5 <label for="star2"></label> 6 <input type="radio" name="rating" value="2" id="star2"> 7 <label for="star3"></label> 8 <input type="radio" name="rating" value="3" id="star3"> 9 <label for="star4"></label> 10 <input type="radio" name="rating" value="4" id="star4"> 11 <label for="star5"></label> 12 <input type="radio" name="rating" value="5" id="star5"> 13</div>

CSS

1/* star rating */2.star-rating {3 width: 100%;4 display: flex;5 justify-content: center;6 align-items: center;7 margin-bottom: 20px;8 font-size: 1.3rem;9}10 11.star-rating input {12 display: none;13}14.star-rating label {15 display: inline-block;16 width: 50px;17 height: 50px;18 margin: 0 5px 0 0;19 background: url(../img/icon/fill_star.png) 0 0 no-repeat;20 background-size: contain;21 cursor: pointer;22}23.star-rating input:checked ~ label {24 display: inline-block;25 width: 50px;26 height: 50px;27 margin: 0 5px 0 0;28 background: url(../img/icon/no_fill_star.png) 0 0 no-repeat;29 background-size: contain;30 cursor: pointer;31}

コメントを投稿

0 コメント