如果图像超过 1 个,我希望图像重叠。但只显示 3 个图像,然后添加一个带有加号的圆形和剩余图像的数量。我的问题是如何以正确的方式重叠它们?
像这样
代码框: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>
)}
最佳答案
在 resellers
容器中呈现所有经销商和 plus 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
}
`;
关于css - 在带样式的组件中使图像重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71760350/