Search code examples
cssreactjsgatsbygatsby-image

Creating an Opaque / transparent gatsby-background-image


CodeSandbox: https://codesandbox.io/s/awesome-gagarin-bss0k?file=/src/pages/index.js


Using gatsby-background-image, I want a transparent background image.

Inline styling does not work. Assinging a class with the opacity I want does not work.

import BackgroundImage from 'gatsby-background-image';
    ...

      <BackgroundImage
        fluid={data.placeholderImage.childImageSharp.fluid}
        Tag="section"
        role="img"
        className="bgImage"
        style={{ opacity: 0.03 }}
      >
        <SEO title="Home" />
        <h1>Hi people - Gatsby3</h1>
        <p>Welcome to your new Gatsby site.</p>
        <p>Now go build something great.</p>
        <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }} />
        <Link to="/page-2/">Go to page 2</Link> <br />
        <Link to="/using-typescript/">Go to "Using TypeScript"</Link>
      </BackgroundImage>
    ...
    .bgImage{
        object-fit: 'contain';
        width: '100%';
        opacity: 0.03;
        background-color: rgba(0,0,0,0.03)
    }

    .bgImage::before{
        opacity: 0.03;
    }

Setting opacity to !important works, but then all the children of the background-image all also transparent. I only want the background image to be transparent.

enter image description here

.bgImage{
            object-fit: 'contain';
            width: '100%';
            opacity: 0.03 !important;
            background-color: rgba(0,0,0,0.03)
        }

I've tried assigning all the children of .bgImage to not be transparent, but it doesn't work, they're all still transparent.

.bgImage * {
        opacity: 1 !important;
    }


I can only get the desired effect I want(of a transparent background with the rest of the site being normal) if I got into my html in the browser and edit a pseudoclass to be

.bgImage.gbi--640152265-sAbmzRF46cBzS5AanAhNU8::before {
z-index: -100;
background-image: url('https://bss0k-44413.sse.codesandbox.io/static/6d91c86c0fde632ba4cd01062fd9ccfa/630fb/gatsby-astronaut.png');
opacity: 0.03;
}

enter image description here

But how would I do this in code?


Solution

  • The opacity of the background image itself is set in the :before pseudoselector of your background container, so you will need to create a selector which include your background image container and accessing directly to you :before, of course, you'll need to use !important in that case... Something like:

    .bgImage::before{
     opacity: .03 !important;
    }
    

    You can override completely the styles by replacing the :after pseudoselector too by:

    .bgImage::after{
     opacity: .03 !important;
    }