Adding text over an image in styled components

Viewed 345

I am having a cart icon which looks like this:

enter image description here

This is an SVG image that I am referencing using the below code:

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

I am implementing dynamic add to cart feature and this would require to add number of products added to cart on the icon. The icon should more or less look like the below image:

enter image description here

This is what I have tried so far:

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

And this is the output I am getting:

enter image description here Is it possible to place this Span on top of the Cart Icon considering it is an SVG file?

1 Answers

sandbox

First I created parent with relative position as below, surrounding both image and number:

<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>

Remember that both parent and image should have same width.

Then I added these css attributes to the image css that you wrote above, in order to place it at the top right corner of the image:

   .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;
  
}
Related