繁体   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