在之前的文章《手把手教你使用CSS3實(shí)現(xiàn)按鈕懸停閃爍動態(tài)特效》中,我們介紹使用CSS3給按鈕添加動態(tài)效果,實(shí)現(xiàn)一個按鈕懸停閃亮陰影動畫效果的方法,感興趣的朋友可以去了解一下~
今天我們我們來看看使用CSS3怎么給文本添加背景圖,讓文字變得生動好看!在我們想要創(chuàng)建一個較大的文本標(biāo)題,但不想使用普通又枯燥的顏色來修飾時,非常有用!
我們先來看看效果圖:
下面我們來研究一下是怎么實(shí)現(xiàn)這個效果的:
首先是HTML部分,定義兩個標(biāo)題
<body> <h1>Hello world!</h1> <h3>Hello world!</h3> </body>
然后開始定義css樣式來進(jìn)行修飾:
body { display: flex; align-items: center; justify-content: center; flex-direction: column; width: 100%; text-align: center; min-height: 100vh; font-size: 100px; font-family:Arial, Helvetica, sans-serif; }
最后就是給文字添加背景圖片:
-
將文字原本的顏色設(shè)置為transparent透明,然后利用background-image屬性給文字加背景圖片
h1 { color: transparent; background-image: url("https://img.php.cn/upload/article/000/000/024/612360451cede816.jpg"); } h3{ color: transparent; background-image: url("https://img.php.cn/upload/article/000/000/024/6124c86e0808b298.jpg"); }
發(fā)現(xiàn)效果是這樣的,不如人意。這是因?yàn)槿鄙倭艘粋€關(guān)鍵屬性background-clip
。background-clip屬性是一個CSS3新屬性,要添加前綴來兼容其他瀏覽器
h1 { color: transparent; background-image: url("https://img.php.cn/upload/article/000/000/024/612360451cede816.jpg"); background-clip: text; -webkit-background-clip: text; } h3{ color: transparent; background-image: url("https://img.php.cn/upload/article/000/000/024/6124c86e0808b298.jpg"); background-clip: text; -webkit-background-clip: text; }
ok,大功告成!下面附上完整代碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> body { display: flex; align-items: center; justify-content: center; flex-direction: column; width: 100%; text-align: center; min-height: 100vh; font-size: 100px; font-family: Arial, Helvetica, sans-serif; } h1 { color: transparent; background-image: url("https://img.php.cn/upload/article/000/000/024/612360451cede816.jpg"); background-clip: text; -webkit-background-clip: text; } h3 { color: transparent; background-image: url("https://img.php.cn/upload/article/000/000/024/6124c86e0808b298.jpg"); background-clip: text; -webkit-background-clip: text; } </style> </head> <body> <h1>Hello world!</h1> <h3>Hello world!</h3> </body> </html>
因?yàn)槲覀兪褂玫氖庆o態(tài)圖片,所以是文本背景圖效果也是靜態(tài)的。如果使用動圖會有動態(tài)效果:
h3 { background-image: url("https://img.php.cn/upload/image/161/146/599/1629799857734746.gif"), url("https://img.php.cn/upload/image/817/380/291/1629799861847258.gif"); background-clip: text; -webkit-background-clip: text; color: transparent; }
PHP中文網(wǎng)平臺有非常多的視頻教學(xué)資源,歡迎大家學(xué)習(xí)《css視頻教程》!