I want to clip the gradient of the parent element to the children but it doesnt quite work. either the gradient shows completely (not only covers the text) or my other, normal background is the background it uses to clip (so completely white).
i basically want the same gradient to be applied to both h1, so the patterns remain
is there a workaround?
<div className="flex flex-col w-full mesh-gradient-background bg-clip-text z-10">
<h1 className="animate-fade-up bg-clip-text text-transparent text-center font-display text-2xl font-bold tracking-[-0.03em] opacity-0 drop-shadow-sm [text-wrap:balance] md:text-5xl md:leading-[5rem] z-[10]"
style={{ animationDelay: "0.15s", animationFillMode: "forwards" }}>
Long Text 1
</h1>
<h1 className="transition-all duration-1000 animate-fade-up text-center font-display text-4xl font-bold tracking-[+0.03em] text-transparent opacity-0 drop-shadow-sm [text-wrap:balance] md:text-7xl md:leading-[5rem] bg-size-200 bg-pos-0 hover:bg-pos-100 w-min cursor-default"
style={{ animationDelay: "0.15s", animationFillMode: "forwards" }}>
Long Text 2
</h1>
</div>
I also tried making the div absolute but the problem remained
2
Answers
To achieve the effect of clipping a gradient background applied to a parent element so that it only covers the text of its children, you can utilize a combination of CSS properties. Specifically, setting the parent to have the gradient background and ensuring that the children are set to be transparent will allow the gradient to show through only the text.
Here’s a possible workaround using CSS:
Ensure the parent element has a gradient background.
Use bg-clip-text and text-transparent on the child elements.
Set the background-clip property on the parent to text for the text to show the gradient.
Make sure you have the following CSS for the gradient background:
Its is a potential bug in Chrome/Edge, though I’m not exactly sure if it disobeyed the draft spec or not. See transform scale not working with background clip and gradients or the issue on Chromium.
If you want the same gradient to be applied to both h1, you can just set the background on
h1
instead. (I’ve changed thedrop-shadow
to make it visible, but you can change it back to whatever you want.) However, if what you meant is to have a shared gradient background, then see the second half of the answer.Either way, you should move the opacity animation to the background
div
instead.After some testing with
isolation:isolate
, it appears to me thatbackground-clip:text
doesn’t count in the child elements that forms a new stacking-context. Hence, any properties on theh1
that causing a new stacking-context to form includingopacity
,z-index
, anddrop-shadow
will make the text being ignored.For
opacity
it is easy to solve in your case. It can be applied to the background itself. And sincez-index
is not needed, just remove it. However, if you need to use drop-shadow, you probably need to use a whole nother approach.