在Tailwind CSS中如何将SVG图标定位到按钮右上角?
解决Tailwind CSS中SVG按钮右上角通知标记的定位问题
你的核心问题是**relative定位容器的位置错误**——当前你把它放在了和SVG同级的空div里,导致绝对定位的小红点参照的是这个空容器,而非SVG图标本身。以下是两种修复方案:
方案一:调整容器结构(额外元素实现)
修正IconBtn组件
给SVG图标包裹一个relative容器,作为绝对定位的参照:
import React, {FC, ElementType, ReactNode} from 'react' interface Props { label: string Icon: ElementType children?: ReactNode } const IconBtn: FC<Props> = ({label, Icon, children}) => { return ( <button type="button" aria-label={label} className="group flex items-center p-2 hover:bg-secondary-50 transition-colors rounded-md cursor-pointer" > <div className="relative"> <Icon className="h-6 w-6 flex-shrink-0 text-secondary-500 group-hover:text-secondary-800" /> {children} </div> </button> ) } export default IconBtn
修正子组件代码
将小红点直接作为IconBtn的子元素,此时它会相对于SVG的父容器定位:
<Link href="/"> <div className="flex justify-center items-center"> <IconBtn label="foo" Icon={NotificationIcon}> <span className="sr-only">notification</span> <div aria-labelledby="notification-tooltip" className="absolute top-0 right-0 w-2 h-2 bg-red-700 rounded-full transform translate-x-1/2 -translate-y-1/2" ></div> </IconBtn> </div> </Link>
添加transform translate-x-1/2 -translate-y-1/2是为了让小红点一半超出SVG右上角,还原GitHub通知标记的视觉效果。
方案二:使用伪元素实现(贴近GitHub的写法)
不需要额外的div元素,直接给SVG的父容器加Tailwind伪元素类:
import React, {FC, ElementType, ReactNode} from 'react' interface Props { label: string Icon: ElementType children?: ReactNode } const IconBtn: FC<Props> = ({label, Icon, children}) => { return ( <button type="button" aria-label={label} className="group flex items-center p-2 hover:bg-secondary-50 transition-colors rounded-md cursor-pointer" > <div className="relative before:content-[''] before:absolute before:top-0 before:right-0 before:w-2 before:h-2 before:bg-red-700 before:rounded-full before:translate-x-1/2 before:-translate-y-1/2"> <Icon className="h-6 w-6 flex-shrink-0 text-secondary-500 group-hover:text-secondary-800" /> {children} </div> </button> ) } export default IconBtn
子组件只需保留屏幕阅读器文本即可:
<Link href="/"> <div className="flex justify-center items-center"> <IconBtn label="foo" Icon={NotificationIcon}> <span className="sr-only">notification</span> </IconBtn> </div> </Link>
内容的提问来源于stack exchange,提问作者GʀᴜᴍᴘʏCᴀᴛ
相关产品推荐
相关产品推荐

