Background image is not showing in Styled Components

Viewed 2761

I was working on a E-commerce application. I was trying to show an overlay Sold Out over the item in my store. Here is my styled components

export const PreviewSoldOut = styled.div`
  div {
    grid-area: preview;
    width: auto;
    max-height: 560px;
    object-fit: contain;
    background-position: center;
    background-image: 
   url("http://localhost:8000/media/products/saleordemoproduct_cuschion01.png");

    img {
      width: 100%;
      object-fit: contain;
    }
  }
`;

Here is my react component

<S.PreviewSoldOut>
   <img src={soldOutThumb}></img>
</S.PreviewSoldOut>

But it's showing only the overlay instead of showing over the product image enter image description here

But I want like this where Sold Out would be over item image

enter image description here

1 Answers

(I don't have enough reputation to comment so I'll make an answer for now.)

Test 1:

Are you sure that the soldOutThumb image has a transparent background?

Test 2:

I believe the issue is due to a nested div in your styled component. Try:

export const PreviewSoldOut = styled.div`
  div {      /* <-------- remove this line */
    grid-area: preview;
    width: auto;
    max-height: 560px;
    object-fit: contain;
    background-position: center;
    background-image: url("http://localhost:8000/media/products/saleordemoproduct_cuschion01.png");

    img {
      width: 100%;
      object-fit: contain;
    }
  }        /* <-------- remove this line */
`;

You may need to adjust the styling a bit after removing the nested div. This worked for me:

import React from "react";
import styled from 'styled-components'
import "./styles.css";

const PreviewSoldOut = styled.div`

    width: auto;
    height: 500px;
    background-image:  url("https://ychef.files.bbci.co.uk/1600x640/p02940bz.jpg");
    background-position: center; /* Center the image */
    background-repeat: no-repeat; /* Do not repeat the image */
    background-size: cover; /* Resize the background image to cover the entire container */

`;

//         
export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <PreviewSoldOut>
        <img src='https://udi.bc.ca/wp-content/uploads/2018/04/Sold-Out-Transparent-300x129.png' />

      </PreviewSoldOut>
    </div>
  );
}
Related