--- tags: CSS, 六角筆記王 title: CSS - 文字取代圖片 --- # CSS - 文字取代圖片 有時候,想讓文字以圖片方式呈現,但又想保留文字時,例如 h1 的文字內容想以 Logo 圖片作呈現,可以這麼做 : ```htmlembedded <h1 class="logo">h1標題內容</h1> ``` ```sass .logo { background-image: url('圖片路徑或網址'); // 確保圖片不會重複 background-repeat: no-repeat; // 盡量與圖片寬高一致,數值只是範例 width: 83px; height: 49px; // 讓文字縮排至 100% 以上 text-indent: 101%; // 讓文字不換行 white-space: nowrap; // 超出範圍的隱藏 overflow: hidden; } ``` 補充說明 : - 若 `h1` 內為 `a` 連結,記得將它設定為 `display: block;` ## SASS/SCSS 寫法 若不想每次都這樣寫,可以將它們寫成 mixin, - textToImage 為自定義名稱 - 使用 `@include` 匯入 - `@include textToImage('圖片位置', ?px, ?px)` ```scss @mixin textToImage($url, $width, $height) { background-image: url($url); background-repeat: no-repeat; width: $width; height: $height; text-indent: 101%; white-space: nowrap; overflow: hidden; } ``` ## 參考來源 > 1. [阿陰 - Day05 「弟兄們,為了SEO!」 ─ 將 h1 圖片取代文字!](https://ithelp.ithome.com.tw/articles/10193599)