添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
被表白的围巾  ·  Cannot read ...·  2 周前    · 
腹黑的领带  ·  Avoid Nesting when ...·  1 周前    · 
豪爽的麦片  ·  Out of date ...·  1 周前    · 
读研的豆芽  ·  <select> – React 中文文档·  2 天前    · 
彷徨的匕首  ·  H5 编辑器 ...·  6 月前    · 
淡定的可乐  ·  RelativeSource ...·  1 年前    · 
乐闻世界logo
搜索文章和话题
中文
基于React创建重叠头像组件,深入理解CSS重叠样式

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

乐闻的头像
乐闻

2023年05月28日 01:26 · 阅读 1597

前言

最近项目有个新需求,需要把用户的头像水平排列并且重叠。本来以为挺麻烦的,刚开始还想着要用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组件

  • 定义组件的接口interface;
  • css
    interface AvatarGroupProps { avatars: Array<string>;
  • 定义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" />; })}