본문 바로가기

Sparta/TIL

23.01.15 TIL-Javascript로 별점 기능 만들기

.star-rating {
  display: flex;
}

.star {
  appearance: none;
  padding: 1px;
}

.star::after {
  content: '☆';
  color: hsl(60, 80%, 45%);
  font-size: 20px;
}​
<body>
  <div class="star-rating">
    <input type="radio" class="star" value="1">
    <input type="radio" class="star" value="2">
    <input type="radio" class="star" value="3">
    <input type="radio" class="star" value="4">
    <input type="radio" class="star" value="5">
  </div>
</body>

 

별점 모양의 HTML, CSS

 

appearance: none을 통해서 라디오 모양을 표시하지 않도록 하고, ::after을 사용하여  빈 별모양을 넣어줬다.

 

.star:hover::after {
  content: '★';
}

.star:has(~ .star:hover)::after {
  content: '★';
}

.star:checked::after,
.star:has(~ .star:checked)::after {
  content: '★';
}

.star:hover ~ .star::after {
  content: '☆';
}

 

그리고 :hover 조건을 통해 ::after에 채운 별모양을 만든다.

 

그 다음 :has()는 괄호안의 선택자에 해당하는 엘리먼트를 가지고 있을 때 활성화된다. 기본값은 자식요소를 찾지만 괄호한에서 ~로 시작한다면 자신 뒤에 있는 요소를 찾는다.

즉 ..star:has(~ .star:hover)는 자신(.star)의 뒤의 요소에 :hovor된 .star가 있다면 활성화된다.

 

라디오의 :checked를 사용해서 체크되어 있는 라디오버튼을 대상으로 할 수 있다.

 

마지막으로 .star:hover ~ .star::after는 :hover되어있는 .star 뒤의 star가 선택됩니다.

 

그리고 이것을 간결하게 쓰기 위해서

 .star:hover::after,
    .star:has(~ .star:hover)::after,
    .star:checked::after,
    .star:has(~ .star:checked)::after {
      content: '★';
    }

 

이런식으로 축약했다.

 

https://solo5star.dev/posts/33/

 

CSS로 별점 기능 만들기

CSS로 별점 기능을 만들어봅시다

solo5star.dev

 

'Sparta > TIL' 카테고리의 다른 글

24.01.18 TIL - node 기초(1)  (0) 2024.01.18
24.01.16 TIL - 배열 내장 메소드  (1) 2024.01.16
24.01.12 TIL - 동기/비동기  (0) 2024.01.12
24.01.11 TIL - 콜백함수(1)  (2) 2024.01.11
24.01.10 TIL-Git  (1) 2024.01.10