想為圖片加上精緻的雙重邊框,並在滑鼠移過時巧妙變色嗎?透過外層容器的邊框搭配圖片本身的內距,就能做出雙框效果,再用 :hover 切換外框顏色,互動感十足。
完整的 HTML 與 CSS 如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
p#outer {
position: relative;
float: left;
margin-top: 20px;
margin-left: 20px;
background: blue;
}
#outer a {
margin: 0;
background-color: blue;
display: block;
position: relative;
border: 2px dashed red;
}
#outer a:hover { border: 2px dashed #CCFFCC; }
#outer img {
display: block;
border: none;
background: #ffffcc;
padding: 4px;
}
</style>
</head>
<body>
<h1>Hover over the image to see the double border effect</h1>
<p id="outer">
<a href="#">
<img src="example.gif" alt="example image border" width="150" height="86" />
</a>
</p>
</body>
</html>原理是這樣的:外層 <a> 有一圈虛線邊框,內層 <img> 則透過 padding 撐出一段淺色留白,於是視覺上就形成「外框 + 內框」的雙重邊框。當滑鼠移到連結上時,:hover 把外框從紅色虛線切換成淺綠色虛線,做出細緻的互動回饋。這完全是純 CSS 的效果,沒有任何腳本,簡單又優雅。