萬盛學電腦網

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

CSS3 Border-image實戰:巧用邊框圖片實現圖片遮罩特效

利用CSS3border-image屬性,配合超大邊框寬度與border-radius: 50%,可零圖層實現圖片圓形遮罩動畫效果。核心代碼結構如下:

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
  <meta charset="utf-8" />
  <title>Border-image遮罩演示</title>
  <style>
    .trans {
      transition: 0.3s ease;  /* 統一過渡 */
    }
    .test_outer {
      display: block;
      width: 200px;
      height: 200px;
      margin: 1em auto;
      position: relative;
      overflow: hidden;
    }
    .test_cover {
      width: 40px;
      height: 40px;
      border: 200px solid rgba(0, 0, 0, .35);  /* 關鍵:超大半透明邊框 */
      border-radius: 50%;
      position: absolute;
      left: -115px;
      top: -165px;
    }
    .test_cover:hover {
      border-color: rgba(0, 0, 0, 0);  /* 懸停時邊框透明,露出底圖 */
    }
  </style>
</head>
<body>
  <div class="test_outer trans">
    <img src="your-image.jpg" alt="目標圖片" style="width:100%; height:100%;">
    <div class="test_cover trans"></div>
  </div>
</body>
</html>

原理解析

  1. 容器定位:.test_outer建立定位上下文,overflow: hidden裁剪溢出邊框。
  2. 遮罩層:.test_cover本體極小(40×40px),但設置border: 200px向外擴展,覆蓋整個容器。
  3. 圓形裁剪:border-radius: 50%將超大邊框剪裁為圓環狀遮罩。
  4. 負偏移定位:left/top負值將遮罩圓心對準容器中心。
  5. 交互觸發:懸停時border-color動畫過渡至全透明,實現「聚光燈」揭示效果。

優勢與擴展

  • 零額外圖片資源,純CSS實現,體積極小
  • 支持transition平滑動畫,體驗流暢
  • 可擴展為點擊展開、多聚光燈、非圓形遮罩(調整border-radius)
  • 兼容性:現代瀏覽器全支持,IE11+部分支持

這項技巧展示了border-image與border-radius組合的創造性應用,值得收藏進CSS奇技淫巧庫。

copyright © 萬盛學電腦網 all rights reserved