Next.js Image component with linear gradient as background
Asked Answered
A

3

6

In the development of my landing page ( with next.js ), i decided to use this line of code as a background of a section.

background-image: linear-gradient(to bottom, rgb(123, 8, 255, 0.9), rgb(123, 8, 255, 0.87)), url("/main background img.jpg");

But, since next.js allows you to use Image component for optimization, i tried to put the same img as background this way

<PresentationHero2>
    {/* Background */}
    <Image
     src="/main background img.jpg"
     alt=""
     layout="fill"
     objectFit="cover"
     />
</PresentationHero2>

Styles ( with styled-components )

export const PresentationHero2 = styles.div`

position: relative;

width: 100%;
height: 663px;
 
background: linear-gradient(to bottom, rgb(123, 8, 255, 0.9), rgb(123, 8, 255, 0.87));

display: flex; 
align-items: center;
justify-content: center;

overflow: hidden;

`;

And everything works fine, the problem is that i can't see the linear-gradient, so, how can i use Image component but using as well the background color ?, because the only thing i can see, is the image sadly :/

I hope you can help me with this. Thanks for your time !

Atterbury answered 1/7, 2021 at 17:27 Comment(0)
A
2

You can create another div with width and height of 100% and put the background (linear gradient )there, so you will be able to see the linear gradient and the img as well !

Atterbury answered 1/7, 2021 at 19:50 Comment(0)
C
4

You need to create another div, set it's z-index to 1 and position to absolute with width and height of 100%. That way, your gradient will be on top of the Next/Image.

<PresentationHero2>
    <div className="radialBackground"></div>
    <Image
     src="/main background img.jpg"
     alt=""
     layout="fill"
     objectFit="cover"
     className="bgImage"
     />
</PresentationHero2>

.radialContainer{
  z-index: 1;
  position: absolute;
  height: 100%;
  width:100%;
  background: linear-gradient(to bottom, rgb(123, 8, 255, 0.9), rgb(123, 8, 255,0.87));
}
.bgImage{
  z-index: 0;
}
City answered 5/2, 2022 at 12:20 Comment(0)
A
2

You can create another div with width and height of 100% and put the background (linear gradient )there, so you will be able to see the linear gradient and the img as well !

Atterbury answered 1/7, 2021 at 19:50 Comment(0)
S
0

For NexJS 13 Image component with Tailwind CSS

<div className="relative overflow-hidden w-64 h-64">
  <Image
  src={backgroundImage}
  alt={alt}
  fill
  className="object-cover w-full h-full bg-[linear-gradient(0deg,rgba(0,0,0,0.75)_6.82%,rgba(0,0,0,0.00)_81.44%)]"
  />
  <div className="absolute w-full h-full bg-[linear-gradient(0deg,rgba(0,0,0,0.75)_6.82%,rgba(0,0,0,0.00)_81.44%)]" /></div>
</div>
Seaboard answered 31/8, 2023 at 8:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.