萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 立體按鈕效果:利用 outset/inset 邊框模擬 3D 按壓反饋

核心原理

利用 CSS border-style 的 outset(外凸)與 inset(內凹)關鍵字,配合 :hover / :active 狀態切換,零圖片實現立體按鈕按壓視覺反饋。

完整代碼

<style>
#elButton a {
  display: block;
  width: 130px;
  padding: 3px 5px;
  margin: 1px;
  font: bold 12px/1.5 Verdana, sans-serif;
  color: #000;
  text-decoration: none;
  text-align: center;
  background-color: #00ffff;
  border: 4px outset aqua;  /* 關鍵:外凸邊框 */
}

#elButton a:hover {
  background-color: #00c0c0;
  padding-left: 4px;        /* 視覺微調 */
  border: 4px inset aqua;   /* 關鍵:懸停時內凹,模擬按下 */
}
</style>

<div id="elButton">
  <a href="#">立體按鈕</a>
</div>

關鍵屬性解析

屬性值作用
border-styleoutset / inset瀏覽器自動計算亮/暗邊框色產生 3D 效果
border-width4px較粗邊框增強立體感
background-color#00ffff → #00c0c0懸停加深色澤增強按下感
padding-left5px → 4px文字微微右移,配合內凹邊框強化按下幻覺

優缺點分析

優點缺點
零圖片、零 JS、代碼極少邊框渲染依賴瀏覽器實現,跨瀏覽器一致性差
語義化 HTML,無障礙友善無法實現複雜漸變、圓角、陰影等現代視覺需求
極佳效能,無重繪開銷觸屏裝置無 :hover 狀態,體驗缺失

現代化重構方案

.btn-3d {
  display: inline-block;
  padding: 12px 24px;
  font: 600 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
  color: #fff;
  text-decoration: none;
  background: linear-gradient(180deg, #00d4d4 0%, #009999 100%);
  border: none;
  border-radius: 6px;
  box-shadow: 
    0 4px 0 #007777,           /* 底部立體厚度 */
    0 6px 12px rgba(0,0,0,.15); /* 投影 */
  transition: transform 0.1s, box-shadow 0.1s;
}

.btn-3d:hover {
  background: linear-gradient(180deg, #00e6e6 0%, #00aaaa 100%);
}

.btn-3d:active {
  transform: translateY(4px);   /* 真實下沉 */
  box-shadow: 
    0 0 0 #007777,
    0 2px 4px rgba(0,0,0,.15);
}

現代方案優勢:transform: translateY 不觸發重排、配合 box-shadow 層次豐富、支援圓角漸變、觸屏可用 :active 觸發。

總結

CSS outset/inset 邊框是早期「無圖片 3D 按鈕」的經典技巧,展示了 CSS 邊框渲染的獨特能力。現代專案應採用 transform + box-shadow + gradient 方案,獲得更可控、更豐富、跨平台一致的立體交互體驗。

copyright © 萬盛學電腦網 all rights reserved