利用 border 三角形拼接 + transform: rotate() 組合成五角星,零圖片、零 SVG、極輕量。
.star {
position: relative;
display: inline-block;
width: 0; height: 0;
border-right: 100px solid transparent;
border-bottom: 70px solid #ffcc00; /* 星星顏色 */
border-left: 100px solid transparent;
transform: rotate(35deg); /* 關鍵旋轉角度 */
}
/* 五角星上半部 (尖角) */
.star::before {
content: "";
position: absolute;
top: -55px; left: -65px;
width: 0; height: 0;
border-bottom: 80px solid #ffcc00;
border-left: 30px solid transparent;
transform: rotate(-35deg);
}
/* 五角星下半部 (凹陷) - 可選,用於描邊效果 */
.star::after {
content: "";
position: absolute;
top: 3px; left: -105px;
width: 0; height: 0;
border-right: 100px solid transparent;
border-bottom: 70px solid #ffcc00;
border-left: 100px solid transparent;
transform: rotate(-70deg);
}
原理:透明邊框形成三角形,旋轉拼接成五角星。尺寸可透過 border-width 縮放。
<fieldset class="rating" aria-label="評分">
<legend>評分</legend>
<input type="radio" id="star5" name="rating" value="5" /><label for="star5" title="5 顆星">★</label>
<input type="radio" id="star4" name="rating" value="4" /><label for="star4" title="4 顆星">★</label>
<input type="radio" id="star3" name="rating" value="3" /><label for="star3" title="3 顆星">★</label>
<input type="radio" id="star2" name="rating" value="2" /><label for="star2" title="2 顆星">★</label>
<input type="radio" id="star1" name="rating" value="1" /><label for="star1" title="1 顆星">★</label>
</fieldset>
radio + label,原生表單語意、鍵盤可操作、無 JS 也能提交。.rating {
display: flex;
flex-direction: row-reverse; /* 視覺順序 1-5,DOM 順序 5-1 */
justify-content: flex-end;
font-size: 2.5rem;
line-height: 1;
color: #ddd; /* 未選中顏色 */
}
.rating input { display: none; } /* 隱藏原生 radio */
.rating label {
cursor: pointer;
transition: color 0.2s, transform 0.1s;
display: block;
padding: 0 2px;
}
.rating label:hover,
.rating label:hover ~ label,
.rating input:checked ~ label {
color: #ffcc00; /* 選中/懸停顏色 */
}
.rating label:active { transform: scale(1.2); }
/* 禁用狀態 */
.rating.disabled label { cursor: not-allowed; opacity: 0.6; }
flex-direction: row-reverse + ~ 兄弟選擇器:滑鼠懸停第 3 顆星,第 1~3 顆同時點亮。input:checked ~ label:已選中狀態持續點亮。title 屬性提供滑鼠懸停提示,螢幕閱讀器讀取 aria-label + value。input,用 aria-label + data-rating="3.5",CSS 計算寬度百分比顯示填滿比例。@keyframes pop { 0% {transform:scale(1)} 50%{transform:scale(1.3)} 100%{transform:scale(1)} } 配合 animation。name="rating" 直接送後端,或 AJAX 更新平均分。fieldset + legend 語意分組。input[type=radio] 有唯一 id,label for 正確關聯。aria-label 描述整體用途。Tab 聚焦、左右鍵 選擇、Enter/Space 確認。prefers-reduced-motion 關閉縮放動畫。純 CSS 即可打造美觀、無障礙、可提交的星級評分元件。配合設計系統 Token 化色彩與尺寸,輕鬆複用至任何專案。更多 CSS 互動元件實戰,請關注本站 UI 元件庫系列。