在带样式的组件中使图像重叠

Make Images Overlap in Styled Components

如果图像超过 1 个,我希望图像重叠。但只显示 3 个图像,然后添加一个带有加号和剩余图像数量的圆形。我的问题是如何以正确的方式重叠它们?

类似这样

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

.reseller class 中添加这样的内容应该可以得到基本效果。

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

如果您想将它们从左到右堆叠,可以使用 z-indexflex-direction 更改它们的渲染顺序。

resellers 容器中呈现所有经销商 加号 div 元素。您需要以相反的顺序渲染头像,以便它们可以正确地“覆盖”右侧的头像。

代码

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

带样式的组件

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

把所有常见的CSS收进“经销商”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
  }
`;