提问人:Katyellen 提问时间:11/13/2023 更新时间:11/13/2023 访问量:25
如何独立于头像的大小定位徽章图标?
How to position badge icon independent the size of the avatar?
问:
我需要构建一个具有徽章的头像组件。问题是根据头像的大小,定位不正确。
在下图中,更容易理解问题所在。你能告诉我如何调整位置,使其无论头像的大小如何都是正确的吗?
这是我放入 codesandbox 的代码
先谢谢你。
import React from "react";
import BadgeSvg from "./BadgeSvg";
import "./avatar.scss";
const Avatar = ({ size }) => {
const image = "https://i.imgur.com/pKHO357.png";
return (
<div>
<div className={`content-icon ${size}`}>
<img
src={image}
alt="Avatar Image"
className={`content-icon ${size}`}
/>
</div>
<div className="badge">
<BadgeSvg size={size} />
</div>
</div>
);
};
export default Avatar;
.content-icon {
display: flex;
justify-content: center;
align-items: center;
gap: 8px;
flex-shrink: 0;
border-radius: 50%;
background-color: #f2f2f2;
object-fit: cover;
color: #999999;
&.xsmall {
width: 16px;
height: 16px;
}
&.small {
width: 32px;
height: 32px;
}
&.medium {
width: 40px;
height: 40px;
}
&.large {
width: 72px;
height: 72px;
}
&.xlarge {
width: 96px;
height: 96px;
}
}
.badge {
position: relative;
top: -18px;
right: -52px;
display: flex;
width: min-content;
}
答:
1赞
Robin
11/13/2023
#1
重新构建 jsx 将解决 css 绝对和相对位置的问题。但是为了实现完美定位,您需要手动计算一些css,例如波纹管。
这是您的组件Avatar
import React from "react";
import BadgeSvg from "./BadgeSvg";
import "./avatar.scss";
const Avatar = ({ size }) => {
const image = "https://i.imgur.com/pKHO357.png";
const getRightValue = (aSize) => {
if (aSize === "medium") {
return { right: "-3px" };
}
if (aSize === "xlarge") {
return { right: "5px" };
}
if (aSize === "large") {
return { right: 0 };
}
};
return (
<div>
<div className={`content-icon ${size}`}>
<img
src={image}
alt="Avatar Image"
className={`content-icon ${size}`}
/>
<div className="badge" style={getRightValue(size)}>
<BadgeSvg size={size} />
</div>
</div>
</div>
);
};
export default Avatar;
这是最后的 css
.content-icon {
position: relative;
/* rest of css */
}
.badge {
position: absolute;
bottom: 0;
}
这是最终的输出,希望这会有所帮助。
评论
.content-icon
position: relative
percentage
bottom: 5%; right: 5%;