LoginSignup
113
98

More than 5 years have passed since last update.

口コミサイトの星(★★★☆☆)をCSSだけで実装してみた

Last updated at Posted at 2016-05-31

star.gif

口コミサイトなどに使えそうな、星をクリックして評価を送信する仕組みをCSSのみで実装しました。
labelタグになっているのでそのままsubmitするだけでデータを送信できます。
また、スマートフォン向けにも同じソースで実装できるので、なるべくワンソースにしたいレスポンシブサイトなんかにも使えると思います。

ソースコード

<form type="get" action="#">
  <div class="evaluation">
    <input id="star1" type="radio" name="star" value="5" />
    <label for="star1"><span class="text">最高</span></label>
    <input id="star2" type="radio" name="star" value="4" />
    <label for="star2"><span class="text">良い</span></label>
    <input id="star3" type="radio" name="star" value="3" />
    <label for="star3"><span class="text">普通</span></label>
    <input id="star4" type="radio" name="star" value="2" />
    <label for="star4"><span class="text">悪い</span></label>
    <input id="star5" type="radio" name="star" value="1" />
    <label for="star5"><span class="text">最悪</span></label>
  </div>
</form>
.evaluation{
  display: flex;
  flex-direction: row-reverse;
  justify-content: center;
}
.evaluation input[type='radio']{
  display: none;
}
.evaluation label{
  position: relative;
  padding: 10px 10px 0;
  color: gray;
  cursor: pointer;
  font-size: 50px;
}
.evaluation label .text{
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  text-align: center;
  font-size: 12px;
  color: gray;
}
.evaluation label:hover,
.evaluation label:hover ~ label,
.evaluation input[type='radio']:checked ~ label{
  color: #ffcc00;
}

YUI Libraryでスタイルをリセットしています。
※ベンダープレフィックスなどは省略しているので、対応させるブラウザに応じて適宜付け足してください。

仕組み

最高→最悪の順でhtmlを記述し、「~」セレクタでcheckedのradioボタン(もしくはhoverしてるlavel)より後続のlabelを黄色くしています。

2016-05-29 13.27.31.png

記載した要素をそのまま横に並べるだけでは、表示は「右に行くにつれ最悪」になってしまいます。
星評価の場合、多くは「右に行くほど評価が高い」と思います。

そこでflex-direction: row-reverse;で表示を反転させることで実現させました。

2016-05-29 13.28.24.png

★以外でも

今回はlabelタグに直接「★」を入れて文字色を変更してるだけですが、labelタグに背景をつけて★以外の図形にもできます。
その場合も上記と同じように、checkedのradioボタン(もしくはhoverしてるlavel)より後続のlabelの背景を変更することで実現できます。

また、inputとlabelの数を増やして半分の★の背景をあてることで0.5ずつ評価させる、といったこともできそうです。

皆さんのアイデアで素敵なwebサイトを作ってください★★★★★

113
98
1

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
113
98