LoginSignup
13
3

More than 3 years have passed since last update.

CSSだけでクリックできるレビューの星(★★★★☆)を作る方法

Posted at

どうも7noteです。レビューや口コミがとても重要な時代になってきましたね。

ホームページでもレビューを見て商品を購入するかどうか決める人がとても増えてきたと思います。
となると実装できないと困りますよね。

そこでCSSだけでできるレビューの星を作って評価できるものを作っていきます。

データを記録させるためにはサーバーと連携させたり、javascriptの組み込みが必要になります。
ここでは見た目の動きについての作り方を解説します。

見本

sample.gif

ソース

index.html
<div class="review">
  <p>レビュー</p>
  <div class="stars">
    <span>
      <input id="review01" type="radio" name="review"><label for="review01"></label>
      <input id="review02" type="radio" name="review"><label for="review02"></label>
      <input id="review03" type="radio" name="review"><label for="review03"></label>
      <input id="review04" type="radio" name="review"><label for="review04"></label>
      <input id="review05" type="radio" name="review"><label for="review05"></label>
    </span>
  </div>
</div>

style.css
.stars span{
  display: flex;               /* 要素をフレックスボックスにする */
  flex-direction: row-reverse; /* 星を逆順に並べる */
  justify-content: flex-end;   /* 逆順なので、左寄せにする */
}

.stars input[type='radio']{
  display: none;               /* デフォルトのラジオボタンを非表示にする */
}

.stars label{
  color: #D2D2D2;              /* 未選択の星をグレー色に指定 */
  font-size: 30px;             /* 星の大きさを30pxに指定 */
  padding: 0 5px;              /* 左右の余白を5pxに指定 */
  cursor: pointer;             /* カーソルが上に乗ったときに指の形にする */
}

.stars label:hover,
.stars label:hover ~ label,
.stars input[type='radio']:checked ~ label{
  color: #F8C601;              /* 選択された星以降をすべて黄色にする */
}

解説

ラジオボタンで星を用意して、選択された星以降の星に色がつくようなCSSをかいていきます。

まず、予め星を逆順に並べますflex-direction: row-reverse;)。そのうえで、input[type='radio']:checked ~ labelの指定をすることでラジオのチェックがついた星以降の星に色が付きます。
逆順に並んでいるので、見た目的には左から順番に色がついているような状態になります。

おそまつ!

~ Qiitaで毎日投稿中!! ~
【初心者向け】HTML・CSSのちょいテク詰め合わせ

13
3
4

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
13
3