본문 바로가기
HTML&CSS

css로 별점 만들기(가상요소 ::before, ::after 활용)

by 작업자C 2023. 3. 11.
728x90

우리가 흔히 쇼핑몰이나 호텔사이트 등 자주 볼 수 있는 별점 평가를 css로 표현해보겠습니다.
가상요소인 ::before와 ::after를 서로 다른 색상으로 겹쳐서 별점의 소수점까지 표현이 가능합니다.

별점 만들기

::before에 베이스를 먼저 만들어준 후, 그 위에 ::after는 별점을 표현합니다.
아래의 예시는 font-size가 50px로 되어있습니다. 즉, 별 하나당 50px이며, 소수점은 0.5점은 50px의 반이므로 25px가 됩니다.
상세한 별점을 표시하고 싶을 때는 ::after의 width의 수치를 조절해주면 됩니다. 별이 5개이므로 최대치는 250px입니다.

<div class="rating"></div>

.rating {
    position: relative;
    font-size: 50px;
}
    
.rating::before{
    content: "★★★★★";
    position: absolute; 
    display: inline-block;
    top: 0;
    left: 0;
    color: #eee;
    white-space: nowrap;    
    line-height: 1em;    
}
    
.rating::after{
    content: "★★★★★";
    position: absolute;
    display: inline-block;
    top: 0;
    left: 0;
    color: #ffd67a;
    white-space: nowrap;     
    line-height: 1em;
    overflow: hidden;
    width: 175px;    
}
5점 width: 250px;
4.5점 width: 225px;
4점 width: 200px;
3점 width: 150px;
2.5점 width: 175px;
2점 width: 100px;
1.5점 width: 75px;
1점 width: 50px;
0.5점 width: 25px;
0점 width: 0px;

이 포스팅은 쿠팡 파트너스 활동의 일환으로 이에 따른 일정액을 수수료를 제공받고 있습니다

728x90