【问题标题】:Adding text over an image in styled components在样式化组件中的图像上添加文本
【发布时间】:2021-08-06 15:50:48
【问题描述】:

我有一个如下所示的购物车图标:

这是我使用以下代码引用的 SVG 图像:

<Nav.Link as={Link} to="/cart" className="pr-0">
     <Image src={cartIcon} className="nav-icon"></Image>
</Nav.Link>

我正在实现动态添加到购物车功能,这需要在图标上添加添加到购物车的产品数量。图标应该或多或少类似于下图:

这是我迄今为止尝试过的:

<Nav.Link as={Link} to="/cart" className="pr-0">
    <Image src={cartIcon} className="nav-icon"></Image>
    <Count> {0}</Count>
</Nav.Link>
   const Count = styled.span`
    -moz-border-radius: 20px;
    border-radius: 20px;
    border: solid black;
    background-color:lightgrey;
    color:black;
    padding-left:3px;
    padding-right:7px;
    padding-top:3px;
    padding-bottom:3px;
    font-size:1.1em;
`;

这是我得到的输出:

考虑到它是 SVG 文件,是否可以将此 Span 放在购物车图标的顶部?

【问题讨论】:

    标签: css reactjs typescript styled-components react-bootstrap


    【解决方案1】:

    sandbox

    首先我创建了具有如下相对位置的父级,围绕图像和数字:

    <div style={{ position: "relative", width: "fit-content" }}>
            <img
              alt="Girl in a jacket"
              style={{ height: "80px", width: 80 }}
              src="https://picsum.photos/200/300"
            />
            <div className="number">1</div>
          </div>
    

    请记住,父级和图像应具有相同的宽度。

    然后我将这些css属性添加到您上面写的图像css中,以便将其放置在图像的右上角:

       .number {
      //placing at top right corner of the parent
      position: absolute;
      top: 0px;
      right: 0px;
    
      //move the number for 50% of its width and height to the top right corner, to 
      //achieve better visual results
      transform: translate(50%, -50%);
      
    
      //other parts of your css :)
      -moz-border-radius: 20px;
      border-radius: 20px;
      border: solid black;
      background-color: lightgrey;
      color: black;
      padding-left: 3px;
      padding-right: 7px;
      padding-top: 3px;
      padding-bottom: 3px;
      font-size: 1.1em;
      
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 2020-05-02
      • 2015-09-14
      • 2017-10-14
      • 2013-01-12
      • 2013-07-29
      • 1970-01-01
      • 2021-09-29
      相关资源
      最近更新 更多