天天看點

好程式員web前端教育訓練系列分享css僞元素的實用技巧我是标題我是标題

  好程式員web前端教育訓練系列分享css僞元素的實用技巧

  1.定義:僞元素用于建立一些不在文檔樹中的元素,并為其添加樣式。比如說,我們可以通過:before :after來在一個元素前、後增加一些文本,并為這些文本添加樣式。雖然使用者可以看到這些文本,但是這些文本實際上不在文檔樹中。

2.僞元素的單雙冒号

在CSS2之前規範不明确的時,僞元素使用單冒号(:)來表示;

在CSS3規範中的要求使用雙冒号(::)表示僞元素,以此來區分僞元素和僞類;但為了向上相容,現在用單冒号(:)也可以的。

3. 使用場景

下面運用before和after在元素前面和後面插入僞元素,實作一些有意思的小效果,代碼和效果圖附上。

3.1用僞元素實作插入文字、字型圖示庫

3.1.1插入文字:

h1:before {

content:"你好"; / 在标題前面插入文字 并設定樣式 /

color: pink;

font-size: 20px;

width: 40px;

height: 40px; }

我是标題

效果如下:

3.1.2插入iconfont字型圖示庫:

@font-face {

font-family: 'iconfont';
src: url('http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.eot');
src: url('http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.eot?#iefix') format('embedded-opentype'),
    url('http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.woff2') format('woff2'),
    url('http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.woff') format('woff'),
    url('http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.ttf') format('truetype'),
    url('http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.svg#iconfont') format('svg');}           
font-family: "iconfont" !important;
/* 一定要加 */
content: "\e601";
color: pink;
font-size: 20px;
width: 40px;
height: 40px;}           

根據效果圖可以看到僞元素是inline元素類型

3.2清除浮動

解決浮動導緻的父元素高度塌陷的問題

.clear:after {

content: "";
 display: block;
 clear: both;           

}

ul{

background:pink;           

li{

float:left;
 margin:0 20px;}           
<li>hello world</li>
 <li>hello world</li>
 <li>hello world</li>
 <li>hello world</li>           

3.3分割線效果

p:before{

content:'';
display:inline-block;
width:100px;
height:2px;
background:pink;
margin:5px;           

p:after{

content:'';
display:inline-block;
width:100px;
height:2px;
background:pink;
margin:5px;           

分割線

效果圖:

3.4對話框效果

div {

width: 180px;
height: 36px;
line-height: 36px;
background: #c0eeff;
border-radius: 5px;
font-size: 14px;
text-align: center;
position: relative;}           

div:before {

content: "";
position: absolute;
top: 10px;
left: -14px;
/* 畫三角形 */
width: 0;
height: 0;
border-top: 10px solid transparent;
border-right: 20px solid #c0eeff;
border-bottom: 10px solid transparent;
border-left: 0 solid #c0eeff;           

快來和我聊天吧~

效果圖如下:

3.5 相片層疊效果

width: 400px;
height: 300px;
border: 8px solid #eee;
position: relative;}           

div img {

width: 100%;
height: 100%;}           

div:before,div:after {

content: "";
position: absolute;
top: 0;
left: 0;
z-index: -1;
width: 400px;
height: 300px;
border: 8px solid #eee;
transform: rotate(8deg);}           

div:after {

transform: rotate(-8deg);}           

總結

使用僞元素能實作的效果非常多,也可以減少網頁中标簽的使用,一起動手試試看僞元素的妙用技巧吧。

繼續閱讀