這個效果乍看像用半透明色塊蓋住圖片,實際上完全靠一個超大的 border 加上圓角完成,非常巧妙。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>圖片遮罩效果</title>
<style type="text/css">
.trans {
-webkit-transition: 0.3s ease;
-moz-transition: 0.3s ease;
-ms-transition: 0.3s ease;
-o-transition: 0.3s ease;
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 {
width: 140px;
height: 140px;
left: -170px;
top: -165px;
}
.test_cover:hover:after {
content: "秋思 - 一葉知秋!";
text-align: center;
margin: 55px 0 0 12px;
color: #fff;
font: bold 16px/1.2 '微軟雅黑';
text-shadow: 1px 1px rgba(0, 0, 0, .35);
position: absolute;
}
</style>
</head>
<body>
<a href="#" class="test_outer">
<span class="test_cover trans"></span>
<img src="此處放入圖片位址" width="200" height="200" />
</a>
</body>
</html>
核心是這幾行:
.test_cover {
width: 40px;
height: 40px;
border: 200px solid rgba(0, 0, 0, .35);
border-radius: 50%;
position: absolute;
left: -115px;
top: -165px;
}
元素本身只有 40×40,卻套了一道 200px 厚的半透明黑 border,再加上 border-radius: 50% 讓邊框內彎成圓形。於是「元素本體」是一個小小的圓洞,而「邊框」則是環繞它的一大片半透明區域——視覺上就變成一個圓形的透明視窗,四周被蒙上一層灰。
接著用負的定位值把這個組合推到圖片外側,讓圓洞剛好落在圖片中央:
.test_outer {
display: block;
width: 200px;
height: 200px;
position: relative;
overflow: hidden;
}
父容器加上 overflow: hidden,把超出畫面的巨大邊框裁掉,剩下的就是我們要的效果。
滑鼠移入時同時放大 width/height 並調整負偏移,圓洞就會擴大;搭配 transition 便成了平順的動畫。而 :hover:after 則在圓洞中央浮現文字。
這段代碼裡的 -ms-、-o- 前綴已無必要,transition 寫成一行即可。另外 left 與 top 的計算若改用 top: 50%; left: 50%; transform: translate(-50%, -50%) 來置中,就不必靠一堆魔法數字去湊,改圖片尺寸時也不用重算——這類「用定位公式取代硬編數字」的習慣,能省下大量後續維護成本。
若目的只是圓形放大檢視,用 clip-path: circle() 會比 border 技巧更直觀;但作為一個理解 border 與 border-radius 互動的練習,這個範例非常精彩。