通用按鈕基礎樣式(重置與規範)
.btn {
/* 重置瀏覽器默認 */
border: none;
background: none;
padding: 0;
margin: 0;
font: inherit;
color: inherit;
text-align: center;
text-decoration: none;
cursor: pointer;
/* 統一規範 */
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
border-radius: 4px;
font-size: 14px;
line-height: 1.5;
padding: 8px 16px;
transition: all 0.15s ease;
white-space: nowrap;
user-select: none;
-webkit-tap-highlight-color: transparent; /* 移動端點擊高亮去除 */
}
五大經典風格變體
1. 主要按鈕
.btn-primary {
background: #007bff;
color: #fff;
border: 1px solid #007bff;
}
.btn-primary:hover { background: #0069d9; border-color: #0062cc; }
.btn-primary:active { background: #0062cc; border-color: #005cbf; }
2. 次要按鈕(外框風格)
.btn-secondary {
background: transparent;
color: #007bff;
border: 1px solid #007bff;
}
.btn-secondary:hover { background: #e7f1ff; }
.btn-secondary:active { background: #d0e4ff; }
3. 危險/刪除按鈕
.btn-danger {
background: #dc3545;
color: #fff;
border: 1px solid #dc3545;
}
.btn-danger:hover { background: #c82333; border-color: #bd2130; }
4. 幽靈按鈕(輕量)
.btn-ghost {
background: transparent;
color: #333;
border: 1px solid transparent;
}
.btn-ghost:hover { background: #f0f0f0; }
.btn-ghost:active { background: #e0e0e0; }
5. 鏈接按鈕(無框)
.btn-link {
background: transparent;
color: #007bff;
border: none;
padding: 4px 8px;
}
.btn-link:hover { text-decoration: underline; }
尺寸變體
.btn-sm { padding: 4px 10px; font-size: 12px; gap: 4px; }
.btn-lg { padding: 12px 24px; font-size: 16px; gap: 10px; }
.btn-block { display: flex; width: 100%; }
圖標按鈕
<button class="btn btn-primary">
<svg class="icon" aria-hidden="true"><use xlink:href="#icon-search"></use></svg>
搜索
</button>
.icon { width: 1em; height: 1em; } /* 隨字體大小縮放 */
載入狀態按鈕
.btn-loading {
position: relative;
color: transparent !important;
pointer-events: none;
}
.btn-loading::after {
content: "";
position: absolute;
width: 1em; height: 1em;
border: 2px solid currentColor;
border-right-color: transparent;
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
無障礙完善
.btn:focus-visible {
outline: 2px solid currentColor;
outline-offset: 2px;
}
.btn:disabled,
.btn[aria-disabled="true"] {
opacity: 0.6;
cursor: not-allowed;
pointer-events: none;
}
相關延伸閱讀
CSS 嵌套寫法與組合選擇器優化指南