使用了 CodePen 作演示,歡迎點擊預覽css
首先來看 MDN 的定義:html
::before 建立一個僞元素,做爲已選中元素的第一個子元素,常經過 content 屬性來爲一個元素添加修飾性的內容。code
::after 建立一個僞元素,做爲已選中元素的最後一個子元素,常經過 content 屬性來爲一個元素添加修飾性的內容。orm
/* CSS3 語法 */ element::before { 樣式 } /* (單冒號)CSS2 */ element:before { 樣式 }
CSS3 引入 :: 用來區分僞類和僞元素。htm
首先看一下基本使用,在 q 標籤的先後加上 « 和 »。ip
<q>Some quotes,</q> he said, <q>are better than none.</q>
q::before { content: "«"; color: blue; } q::after { content: "»"; color: red; }
繪製一個缸的正面圖形。element
<div class='vat'></div>
.vat { width: 160px; height: 160px; border-radius: 160px; background-color: #919191; position: relative; } .vat::before { content: ""; width: 160px; height: 40px; background-color: white; position: absolute; } .vat:after { content: ""; width: 160px; height: 10px; background-color: white; position: absolute; bottom: 0; }
vatget
繪製一個圓形方孔的圖形。it
<div class="money"></div>
.money { width: 160px; height: 160px; border-radius: 160px; background-color: #8b653a; position: relative; } .money:after { content: ""; width: 50px; height: 50px; background-color: white; position: absolute; bottom: 55px; left: 55px; }
一個簡單的代辦清單,奇數次點擊可打鉤,偶數次點擊取消打鉤。
<ul> <li>Buy milk</li> <li>Take the dog for a walk</li> <li>Exercise</li> <li>Write code</li> <li>Play music</li> <li>Relax</li> </ul>
li { list-style-type: none; position: relative; margin: 2px; padding: 0.5em 0.5em 0.5em 2em; background: lightgrey; font-family: sans-serif; } li.done { background: #CCFF99; } li.done::before { content: ''; position: absolute; border-color: #009933; border-style: solid; border-width: 0 0.3em 0.25em 0; height: 1em; top: 1.3em; left: 0.6em; margin-top: -1em; transform: rotate(45deg); width: 0.5em; }
var list = document.querySelector('ul'); list.addEventListener('click', function(ev) { if( ev.target.tagName === 'LI') { ev.target.classList.toggle('done'); } }, false);
[1] ::before