這個技巧的原理很巧妙:用一個超大的半透明 border 當遮罩,再靠圓角與定位把它蓋在圖片上,完全不需要額外的圖片素材。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>border 遮罩效果</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="your-image.jpg" width="200" height="200" />
</a>
</body>
</html>
核心在 .test_cover 這幾行:
.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 寬、黑色 35% 不透明的巨大邊框。加上 border-radius: 50% 之後,這圈邊框的內緣形成一個圓形視窗,再用絕對定位把它推到圖片上方,遮罩效果就出現了。
外層容器接著把超出部分收掉:
.test_outer {
display: block;
width: 200px;
height: 200px;
position: relative;
overflow: hidden;
}
overflow: hidden 是關鍵,少了它,那圈 200px 的邊框會直接撐破版面。
滑過時把內容區從 40px 放大到 140px,同時調整 left 讓圓心維持在同一位置,圓形視窗就「擴張」了。再用 :after 的 content 塞入文字,搭配文字陰影提高在淺色背景上的可讀性。
因為 .trans 已宣告 transition,尺寸與位置的變化會被補上 0.3 秒的緩動,整個過程看起來就是一個平滑的圓形放大動畫。
這個做法的優點是純 CSS、無需 JavaScript、也不需要預先準備遮罩圖;要調整遮罩濃淡只改 rgba 的透明度,要改視窗形狀則換 border-radius 即可,彈性相當高。