LoginSignup
22
22

More than 5 years have passed since last update.

CSSだけで星形レーティング(小数点スコアも対応version)

Last updated at Posted at 2016-10-18

目的

  • 満点が星3個の時の星1.5個を表現する
  • こんな感じ。スクリーンショット 2016-10-18 19.29.09.png

コード

star.html
...
<div class="star-rating-box">
    <div class="empty-star">
    ☆☆☆
    </div>  
    <div class="filled-star">
    ★★★
    </div>  
</div>
...
star.css
.star-rating-box {
    position: relative; /* position: abosoluteの基準 */
    display: inline-block; /* 最大星数に応じてdivのwidthを伸縮させるため */
}
.filled-star {
    position: absolute; /* .filled-starと.empty-starを重ねる */
    top: 0; /* 左上の基準位置に移動させる */
    overflow: hidden; /* widthが足りない時、はみ出た分は表示しない */
    white-space: nowrap; /* widthが足りない時に、折り返さないようにする。 */
    width: 50%; /* 星1.5個 表示。= 100 * 1.5 / 3 */ 
}

解説

  • 欠けた星を表現するためにoverflow: hiddenwhite-space: nowrapwidth: xx%を.filled-starに指定するところがコツ。widthを小さくして、わざと星をdiv.filled-starからはみ出させる。はみ出た分は見えないため、ユーザーには欠けた星が認識される。
  • ratingが満点の場合=widht: 100%。あとは、ratingに比例してwidthの%を変化させて使用する

GlyphiconやFont Awsomeを使う!

☆と★を下記置き換えるだけ。
* ☆

Font Awsomeの場合
<i class="fa fa-star-o" aria-hidden="true"></i>
Glyphiconの場合
<span class="glyphicon glyphicon-star-empty"></span>
Font Awsomeの場合
<i class="fa fa-star" aria-hidden="true"></i>
Glyphiconの場合
<span class="glyphicon glyphicon-star"></span>

注意

  • div.star-rating-boxのwidth属性を指定すると、星の欠け具合が.filled-starのwidthと比例しなくなるかも。 display: inline-blockを指定したことで多分大丈夫。

応用

  • widthをtransition-propertyにすれば星がにゅーっと出てくるアニメーションができます。
  • 今回の例では、白抜きの星の部分にカーソルを合わせると星が塗られてきます。

https://gyazo.com/5b9791b1aa9801d6ddb7610d867f2c0f

star-transition.css
.star-rating-box {
    position: relative; /* position: abosoluteの基準 */
}
.filled-star {
    position: absolute; /* .filled-starと.empty-starを重ねる */
    top: 0;
    overflow: hidden; /* widthが足りない時、はみ出た分は表示しない */
    white-space: nowrap; /* widthが足りない時に、折り返さないようにする。 */
    width: 0%; /* 変更箇所 widthの初期値 */
    transition-property: width; /* 追加箇所 */
    transition-duration: 0.5s; /* 追加箇所 */
}

 /* 追加箇所 */
.empty-star:hover + .filled-star {
    width: 50%; /* 星1.5個 表示。= 100 * 1.5 / 3 */ 
}
  • 実際は、星の数やスコアを可変にしたいので、railsであればヘルパーなどを使って実装するとよいでしょう。

参考

以下駄文

  • 見た目が華やかになる応用編もつけたら面白いかなとおもって、使ったこともないtransitionに手を出したら、文書書き上げるのに時間がかかった。原因は、トリガをページ読み込み終了にしようと色々調べたこと(しかも、出来ず。)。javascriptを使えば余裕で出来るんだけど、それじゃ、タイトル詐欺になるので、CSSだけでなんとかしたかった。
  • 星形レーティングの表示のトリガーがhoverっておかしいのはわかっているのです。ただ、animationのタイミングまで理解仕切れなかった。
22
22
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
22
22