【问题标题】:Background image is not showing in Styled Components背景图像未在样式化组件中显示
【发布时间】:2020-12-23 02:54:24
【问题描述】:

我正在开发一个电子商务应用程序。我试图在我商店中的商品上显示叠加层Sold Out。这是我的样式组件

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;
    }
  }
`;

这是我的反应组件

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

但它只显示叠加层,而不是显示在产品图片上

但我想要这样 Sold Out 会超过商品图片

【问题讨论】:

    标签: html css reactjs typescript styled-components


    【解决方案1】:

    (我没有足够的声誉来发表评论,所以我现在会回答。)

    测试 1:

    您确定soldOutThumb 图像具有透明背景吗?

    测试 2:

    我认为问题是由于您的样式组件中嵌套了div。试试:

    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 */
    `;
    
    

    删除嵌套的 div 后,您可能需要稍微调整样式。这对我有用:

    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>
      );
    }
    

    【讨论】:

    • 谢谢,但soldOutThumb 确实有透明背景。我已经编辑了我的帖子。
    猜你喜欢
    • 1970-01-01
    • 2011-06-09
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2019-02-11
    • 2019-08-08
    相关资源
    最近更新 更多