基于React创建重叠头像组件,深入理解CSS重叠样式

前言

最近项目有个新需求,需要把用户的头像水平排列并且重叠。本来以为挺麻烦的,刚开始还想着要用JS去计算每一个头像需要位移的距离。

其实这个需求只需要一行代码就能搞定。最终的效果图如下:

效果图

实现方案

首先定义HTML代码结构

ts
import React from "react"; import "./index.less"; const avatars = [ "<https://upload.jianshu.io/users/upload_avatars/10174664/6edf3306-4758-4472-90b8-dfc214d6f028.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/80/h/80/format/webp>", "<https://upload.jianshu.io/users/upload_avatars/10174664/6edf3306-4758-4472-90b8-dfc214d6f028.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/80/h/80/format/webp>", "<https://upload.jianshu.io/users/upload_avatars/10174664/6edf3306-4758-4472-90b8-dfc214d6f028.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/80/h/80/format/webp>", "<https://upload.jianshu.io/users/upload_avatars/10174664/6edf3306-4758-4472-90b8-dfc214d6f028.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/80/h/80/format/webp>", "<https://upload.jianshu.io/users/upload_avatars/10174664/6edf3306-4758-4472-90b8-dfc214d6f028.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/80/h/80/format/webp>", "<https://upload.jianshu.io/users/upload_avatars/10174664/6edf3306-4758-4472-90b8-dfc214d6f028.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/80/h/80/format/webp>", ]; export default function AvatarPage() { return ( <div className="avatar"> {avatars.map((avatar) => { return <img className="avatar-item" src={avatar} alt="avatar" />; })} </div> ); }

1. 使用负边距

使用margin-left负值实现水平重叠的效果。除了第一个mage元素外都设置负边距。

cs
.avatar { display: flex; } .avatar-item { height: 56px; width: 56px; border-radius: 100%; border: 4px solid #efefef; box-shadow: 0 0 5px 2px rgba(0, 0, 0, 0.1); &:not(:first-child) { // 只需要加这行代码就能搞定 margin-left: -24px; } }

2. 使用相对定位

使用相对定位实现,将每个头像相对于父容器进行定位,然后设置负的left值来实现水平重叠效果。

css
.avatar { display: flex; } .avatar-item { height: 56px; width: 56px; border-radius: 100%; border: 4px solid #efefef; box-shadow: 0 0 5px 2px rgba(0, 0, 0, 0.1); // 父容器设置定位属性 position: relative; z-index: 1; &:not(:first-child) { //子元素设置定位属性 position: relative; left: -24px; z-index: 2; } }

封装React组件

  1. 定义组件的接口interface;
css
interface AvatarGroupProps { avatars: Array<string>; }
  1. 定义React组件代码;
css
import React from "react"; import "./index.less"; export default function AvatarGroup(props:AvatarGroupProps) { const { avatars } = props; return ( <div className="avatar"> {avatars.map((avatar) => { return <img className="avatar-item" src={avatar} alt="avatar" />; })} </div> ); }

总结

合理利用CSS属性,实现DOM元素水平重叠效果,提高页面的交互性和用户体验。抽取React组件以达到最快的代码复用效果。