pr -
pr -

Reputation: 358

Why doesn't gradient text work in JavaScript?

I'm trying to make gradient text with javascript and CSS. The text is not showing, and if I remove -webkit-background-clip, the text is black, not gradient. Here is my code:

let gradientText = document.getElementById('title');
gradientText.style.background = '-webkit-linear-gradient(#ccc, #000)';
#title {
    font-size:40px;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
<h1 id="title">Gradient text</h1>

Upvotes: 0

Views: 299

Answers (2)

Martin Godzina
Martin Godzina

Reputation: 1575

You have also set the webKitBackgroundClip in your js code to make it work:

let gradientText = document.getElementById('title');
gradientText.style.background = '-webkit-linear-gradient(#eee, #333)';
gradientText.style.webkitBackgroundClip = 'text'; // this is important
#title {
    background: -webkit-linear-gradient(#ccc, #000);
    font-size:40px;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
<h1 id="title">Gradient text</h1>

Upvotes: 1

esqew
esqew

Reputation: 44699

It seems you've got your rules applied a bit out-of-order. Set the background property before setting the background clipping and text fill colors:

#title {
    background: -webkit-linear-gradient(#ccc, #000);
    font-size:40px;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
<h1 id="title">Gradient text</h1>

Upvotes: 4

Related Questions