看到範例效果,你也許以為那只是一張帶文字的圖片。用滑鼠去選取文字試試——發現了吧?那其實是圖片與文字的真正組合。下面我就來說明它是怎麼做到的。
先來看結構程式碼(節錄):
<div id="info">
<h2>TRACKING YOUR IMAGES</h2>
<div id="holdit">
<img src="/imagelist/06/24/4fnpgj5042e6.jpg" alt="Winnie the pooh" />
<em class="a420"></em>
<em class="a430"></em>
…(多個不同寬度的 em)…
<p>"I shall have to wait until I catch up with it," said Winnie-the-Pooh. …</p>
</div>
</div>
對應的 CSS:
#holdit { width:700px; position:relative; margin:3em auto; padding:10px; border:1px solid #ddd; }
#holdit img { position:absolute; z-index:1; top:10px; left:10px; }
#holdit p { margin:0; position:relative; z-index:10; line-height:18px; text-align:justify; font-size:10px; }
#holdit em { display:block; float:left; height:18px; clear:left; overflow:hidden; }
.a230 {width:230px;} .a240 {width:240px;} .a250 {width:250px;}
.a270 {width:270px;} .a300 {width:300px;} .a340 {width:340px;}
…(依此類推,定義各段 em 的寬度)…
首先,把容器 #holdit 設為相對定位,確保後面的 img 絕對定位時以它左上角為原點。
接著把 #holdit 裡的 img 設為絕對定位、z-index 為 1,這樣圖片就脫離了文件流。
然後把 em 標籤設為左浮動,高度與 p 的 line-height 一致,再依圖片的輪廓分別設定每個 em 的寬度(記得用 clear 清除浮動)。這些 em 就像一道道「看不見的隔板」,把文字擠到圖片旁邊,形成繞排的效果。
最後把 p 設為相對定位、z-index 設得比 img 大,讓文字浮在圖片之上。
其實還有個更省事的做法:直接把圖片設為 #holdit 的背景,就不必另外為 img 寫 CSS 了。