Joseph
Joseph

Reputation: 7785

Make Images Overlap in Styled Components

I wanted the images to overlap if images is more than 1. But only show 3 images, then add a circular shape with a plus and the number of images left. My problem is how do I overlap them the correct way?

Something like this

enter image description here

Codesandbox: CLICK HERE

    <div className="resellers">
      {images.slice(0, 2).map((image, i) => (
        <span className="reseller" key={i}>
          <img src={image} alt="" />{" "}
        </span>
      ))}
    </div>
    {images.length > 2 && (
      <div className="plus">
        <span> + {images.length - 2} </span>
      </div>
    )}

Upvotes: 3

Views: 691

Answers (2)

Drew Reese
Drew Reese

Reputation: 203471

Render all the reseller and the plus div elements within the resellers container. You'll want to render the avatars in reverse order so that they can correctly "overlay" the avatar to the right.

Code

<Resellers>
  {!!images.slice(2).length && (
    <ResellerPlus>
      <span>+ {images.slice(2).length}</span>
    </ResellerPlus>
  )}
  {images
    .slice(0, 2)
    .reverse()
    .map((image, i) => (
      <Reseller key={i}>
        <img src={image} alt="reseller" />
      </Reseller>
    ))}
</Resellers>

Styled Components

const Resellers = styled.div`
  display: flex;
  align-items: center;
  flex-direction: row-reverse; // <-- un-reverse avatars
`;

Collect all the common CSS into the "reseller" div.

const Reseller = styled.div`
  align-items: center;
  color: #fff;
  background-color: #bdbdbd;
  border: 4px solid #fff;      // <-- white space around
  border-radius: 50%;          // <-- circle divs
  display: flex;
  flex-direction: row;
  font-family: Nunito-Bold;
  font-size: 1rem;
  height: 40px;
  overflow: hidden;            // <-- hide edges of images
  text-align: center;          // <-- center text
  width: 40px;

  :not(:first-child) {
    margin-right: -0.5rem;     // <-- apply overlap
  }

  img {
    margin-right: 0.5rem;
    object-fit: contain;
  }
`;

const ResellerPlus = styled(Reseller)`
  font-family: Nunito-SemiBold;

  span {
    width: 100%;               // <-- help center text
  }
`;

Edit make-images-overlap-in-styled-components

enter image description here

Upvotes: 3

bluecouch
bluecouch

Reputation: 193

Adding something like this to the .reseller class should get the basic effect.

.reseller {
   margin-right: -15px;
   border-radius: 100%;
   border: solid white 3px;
}

If you want to stack them left in front of right, you can use z-index or flex-direction to change the order they are rendered at.

Upvotes: 0

Related Questions