Home > Blockchain >  Placing a gradient background on an image with transparent background
Placing a gradient background on an image with transparent background

Time:05-11

What I would like to achieve is basically have a gradient appear on the text as opposed to the background of an image. I have created an example here: https://codepen.io/BenSagiStuff/pen/BaYKbNj

body{
  background: black;
}

img{
  padding: 30px;
  background: linear-gradient(to right, #E50000 8%, #FF8D00 28%, #FFEE00 49%, #008121 65%, #004CFF 81%, #760188  100%);
}
<img src="https://upload.wikimedia.org/wikipedia/commons/9/95/Transparent_google_logo_2015.png" >

As you can see, currently the background of the image has the gradient, but, what I would like is for the text "Google" to have the gradient and the background of the png should stay as black.

Ultimately the goal would be to have the gradient transition underneath the image as well, so the gradient slides horizontally under the image as well.

CodePudding user response:

Use the image as a mask on a common element

body{
  background: black;
}

.box{
  --img:url(https://upload.wikimedia.org/wikipedia/commons/9/95/Transparent_google_logo_2015.png);
  
  width:300px;
  aspect-ratio:3;
  background: linear-gradient(to right, #E50000 8%, #FF8D00 28%, #FFEE00 49%, #008121 65%, #004CFF 81%, #760188  100%);
  -webkit-mask: var(--img) 50%/cover;
          mask: var(--img) 50%/cover;
}
<div ></div>

CodePudding user response:

There's a little problem with your implementation.

PNG is transparent, but it's a square piece of image. You might be successful using a svg image or just applying this gradient background in a text tag.

on your HTML you make this way:

<div>
<h1>Google</h1>
</div>

Your CSS this way

body{
  background: black;
  font-family:helvetica;
}

h1{
    background: linear-gradient(to right, #E50000 8%, #FF8D00 28%, #FFEE00 49%, #008121 65%, #004CFF 81%, #760188  100%);
   font-size: 160px;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
div {
  display:flex;
}

It's also better for performance.

Also, you can animate easily.

Such as the example in this codepen https://codepen.io/shshaw/pen/YpERQQ

:)

  • Related