簡體   English   中英

如何使用 CSS 偽元素 (:after) 添加圖像作為文本背景

[英]How to add an image as a text background using CSS pseudo element (:after)

是否可以使用偽元素作為 HTML 文本元素 (h1) 的背景?

我知道將圖像用作文本背景的簡單方法是使用background-clip: text; 屬性直接,但在我的情況下,我需要將一些額外的 css 屬性應用到背景圖像(旋轉,也許還有一些過濾器屬性),因此,我不能直接應用這些 css 屬性,因為它們將應用於文本元素也是如此。

我認為:after偽元素可以做到這一點,但我沒有任何成功。

假設這是我的h1包裹在 div 中:

<div class="wrapper">
  <h1>My title that should have an image background</h1>
</div>

這是我試過的css:

.wrapper {
  width: 100vw;
  height: 400px;
}

.wrapper h1 { 
  position: relative;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.wrapper h1:after {
  content: '';
  position: absolute;
  background-image: url(https://picsum.photos/200);
  background-position: 50% 50%;
  background-repeat: no-repeat;
  transform: rotate(-3deg); /* the image is required to be rotated */
  background-size: cover;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

https://jsfiddle.net/8ztcuv12/

預期結果 L 在此處輸入圖片說明

有沒有更好的方法來實現這一目標? 歡迎任何解決方案。

您可以在包裝器上使用backround-image以便如果您想旋轉heading
它也不旋轉圖像。

 .wrapper { width: 100vw; height: 100px; position: relative; } .wrapper h1 { transform: rotate(-3deg); } .wrapper:after { content: ''; position: absolute; background-image: url(https://picsum.photos/200); background-position: 50% 50%; background-repeat: no-repeat; transform: rotate(-3deg); /* the image is required to be rotated */ background-size: cover; left: 0; top: 0; width: 100%; height: 100%; z-index: -1; }
 <div class="wrapper"> <h1>My title that should have an image background</h1> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM