[英]How to add an image as a text background using CSS pseudo element (:after)
Is it possible to use a pseudo-element as a background for an HTML text element (h1)?是否可以使用伪元素作为 HTML 文本元素 (h1) 的背景?
I know that the simple way of using an image as a text background is using the background-clip: text;
我知道将图像用作文本背景的简单方法是使用
background-clip: text;
property directly, but in my case, I need to apply some additional css properties to the background image (rotation and maybe some filter properties as well), and because of this, I cannot apply those css properties directly, as they will be applied to the text element as well.属性直接,但在我的情况下,我需要将一些额外的 css 属性应用到背景图像(旋转,也许还有一些过滤器属性),因此,我不能直接应用这些 css 属性,因为它们将应用于文本元素也是如此。
I think that :after
pseudo element can do this, but I don't have any success.我认为
:after
伪元素可以做到这一点,但我没有任何成功。
Let's say that this is my h1
wrapped in a div:假设这是我的
h1
包裹在 div 中:
<div class="wrapper">
<h1>My title that should have an image background</h1>
</div>
And this is the css I've tried:这是我试过的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/ https://jsfiddle.net/8ztcuv12/
Is there a better way of achieving this?有没有更好的方法来实现这一目标? Any solutions are welcome.
欢迎任何解决方案。
You can use backround-image
on wrapper so that if you want to rotate heading
.您可以在包装器上使用
backround-image
以便如果您想旋转heading
。
It don't rotate image too.它也不旋转图像。
.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.