:before和:after的作用就是在指定的元素內容(而不是元素本身)之前或者之後插入一個包含content屬性指定內容的行內元素,最基本的用法如下:
#example:before {
content: "#";
color: red;
}
#example:after {
content: "$";
color: red;
}
這段代碼會在#example元素內容之前插入一個'#',以及在內容之後添加一個'$',插入的行內元素是作爲#example的子元素,效果如下:
Here is the example content
需要注意的是如果沒有content屬性,僞類元素將沒有任何作用。但是可以指定content爲空,同時正如前面所說,插入的內容默認是一個行內元素,並且在HTML源代碼中無法看到,這就是爲什麼稱之爲僞類元素的理由,所以也就無法通過DOM對其進行操作。
#example:before {
content: "";
display: block;
width: 100px;
height: 100px;
}
僞類元素也會像其他子元素一樣正常繼承父元素的一些CSS屬性,比如字體等。
除了插入文字內容,還可以指定其他內容:
p:before {
content: url('img.jpg');
}
a:after {
content: attr(href);
}
attr()函數會返回指定元素對應屬性的值