近來較完整地看完了 CSS 的一些文檔,大部分樣式運用都沒問題,只是有些較陌生。本篇學習筆記主要針對 :before 和 :after 這兩個偽元素,另外會略微帶過幾個實用的小樣式。
什麼是 :before 和 :after?該如何使用?
:before 是 CSS 中的一種偽元素,可用於在某個元素之前插入內容;:after 則是在元素之後插入內容。
先跑個簡單的代碼測試效果:
<style> p:before{ content: "H" /*:before 和 :after 必帶 content 屬性*/ } p:after{ content: "d" } </style> <p>ello Worl</p>
以上代碼會在頁面中呈現 "Hello World"。透過瀏覽器的「審查元素」看到的內容是:
<p> ::before "ello Worl" ::after </p>
也就是 p 標籤內容前面會插入一個包含 "H" 的 :before 偽元素,後面則插入包含 "d" 的 :after 偽元素。
1. 結合 border 製作對話框樣式。
先了解如何用 border 畫三角形:
<style> .triangle{ width: 0; height: 0; border-left:50px solid red; border-bottom:50px solid blue; border-top:50px solid black; border-right:50px solid purple } </style> <div class="triangle"></div>
這會顯示一個由四個三角形組成的正方形。若把其他三邊設為透明,只留一邊顯示顏色,就能得到一個三角形:
.triangle{ width: 0; height: 0; border:50px transparent solid; border-top-color: black; /* 其餘三邊保持透明 */ }
接著加上 :before 製作對話框:
<style> .test-div{ position: relative; width:150px; height:36px; border-radius:5px; border:black 1px solid; background: rgba(245,245,245,1) } .test-div:before{ content: ""; display: block; position: absolute; top:8px; width: 0; height: 0; border:6px transparent solid; left:-12px; border-right-color: rgba(245,245,245,1); } </style> <div class="test-div"></div>
此時會出現類似微信/QQ 的對話框,但突出的三角形上還缺一點邊框。用 :after 來補救:
<style> .test-div{ position: relative; width:150px; height: 36px; border:black 1px solid; border-radius:5px; background: rgba(245,245,245,1) } .test-div:before,.test-div:after{ content: ""; display: block; position: absolute; top:8px; width: 0; height: 0; border:6px transparent solid; } .test-div:before{ left:-11px; border-right-color: rgba(245,245,245,1); z-index:1 } .test-div:after{ left:-12px; border-right-color: rgba(0,0,0,1); z-index: 0 } </style> <div class="test-div"></div>
這樣一個完整的對話框樣式就呈現在眼前了。至於三角形方向,只要調整 position 位置與 border 顯示顏色的方位即可。
2. 作為內容的半透明背景層。
例如製作一個半透明的登錄框:
<style> body{ background: url(img/1.jpg) no-repeat left top } .test-div{ position: relative; width:300px; height: 120px; padding: 20px 10px; font-weight: bold; } .test-div:before{ position: absolute; content: ""; top:0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,.5); z-index:-1 } </style> <div class="test-div"> <table> <tr> <td>Name</td> <td><input placeholder="your name" /></td> </tr> <tr> <td>Password</td> <td><input placeholder="your password" /></td> </tr> <tr> <td></td> <td><input type="button" value="login" /></td> </tr> </table> </div>
:before 和 :after 還有更多巧妙用法,例如搭配 CSS3 動畫實現漂亮的動態效果(如 HoverEffectIdeas)。
position 定位問題
position 屬性規定了元素的定位類型,預設為 static,其他值包括:
absolute:相對第一個非 static 定位的父元素進行絕對定位;
fixed:相對瀏覽器窗口定位;
relative:相對自身正常位置定位;
inherit:從父元素繼承 position 值。
z-index 元素堆疊排序
z-index 用於設置堆疊順序,數值越大層級越高。
zoom 元素縮放比例
zoom 適用於所有元素,用於設置縮放比例,原比例為 1。
em 和 rem 的區別
1em 等於當前字體尺寸,且會被子元素繼承;rem = root em,相對於 HTML 根元素的字體大小進行相對調整。
今天暫時寫到這裡,明天就是元旦了,可以好好休息。元旦快樂~