前面的話
CSS以圖換字的技術,很久都沒人提起了。它是一種在h1標簽內,使用圖像替換文本元素的技術,使頁面在設計和可訪問性之間達到平衡。本文將詳細介紹CSS以圖換字的9種方法
文字隱藏
在h1標簽中,新增span標簽來保存標題內容,然后將其樣式設置為display:none
| <style> h1 { width: 64px; height: 64px; background: url(https://static.xiaohuochai.site/icon/icon_64.ico); font: 12px/1 '微軟雅黑'; } span { display: none; } </style> <h1> <span>小火柴的藍色理想</span> </h1> | 
負縮進
通過使用text-index:-9999px,這樣一個比較大的負縮進,使文本移到頁面以外的區域
| <style> h1 { width: 64px; height: 64px; background: url(https://static.xiaohuochai.site/icon/icon_64.ico); font: 12px/1 '微軟雅黑'; text-indent:-9999px; } </style> <h1>小火柴的藍色理想</h1> | 
負margin
通過使用margin-left:-2000px,使盒模型向左偏移2000px,然后將寬度設置為2064px,從而頁面中只顯示2064px中64px的部分。將圖片的背景設置為右對齊,且不重復
| <style> h1 { width: 2064px; height: 64px; background: url(https://static.xiaohuochai.site/icon/icon_64.ico) right no-repeat; font: 12px/1 '微軟雅黑'; margin-left:-2000px; } </style> <h1>小火柴的藍色理想</h1> | 
上padding
因為背景是顯示在padding-box區域中的,而文本是顯示在content-box區域中。所以,將height設置為0,用padding-top來替代height,并設置overflow:hidden。則,可以只顯示背景不顯示文本
| <style> h1 { width: 64px; padding-top: 64px; height:0; overflow:hidden; background: url(https://static.xiaohuochai.site/icon/icon_64.ico); font: 12px/1 '微軟雅黑'; } </style> <h1>小火柴的藍色理想</h1> | 
0寬高
通過新增一個span標簽來保存文本內容,并將該標簽的寬高設置為0,再設置溢出隱藏即可
| <style> h1 { width: 64px; height: 64px; background: url(https://static.xiaohuochai.site/icon/icon_64.ico); font: 12px/1 '微軟雅黑'; } span{display:block;width: 0;height:0;overflow:hidden;} </style> <h1><span>小火柴的藍色理想</span></h1> | 
文本透明
設置文本的顏色為transparent,并設置font-size為1px,即減少行高的影響
| <style> h1 { width: 64px; height: 64px; background: url(https://static.xiaohuochai.site/icon/icon_64.ico); color:transparent; font-size:1px; } </style> <h1>小火柴的藍色理想</h1> |