Search code examples
reactjstailwind-css

In Tailwind what is the correct way to move a SVG to top right over a button?


Learning Tailwind CSS trying to figure out what is the correct way to move an SVG icon to the top right over a button? This is a similar behavior to the notifications on Github and when looking at their code they're using :before. Applying top-0 and inset-y-0 moved the div to the top of the layout.

Research

Attempt

BtnIcon component:

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"
    >
      <Icon className="h-6 w-6 flex-shrink-0 text-secondary-500 group-hover:text-secondary-800" />
      {children}
    </button>
  )
}

export default IconBtn

child:

<Link href="/">
  <div className="flex justify-center items-center">
    <IconBtn label="foo" Icon={NotificationIcon}>
      <span className="sr-only">notification</span>
      <div className="relative">
        <div
          aria-labelledby="notification-tooltip"
          className="absolute top-0 right-0 w-2 h-2 bg-red-700 rounded-full"
        ></div>
      </div>
    </IconBtn>
  </div>
</Link>

Solution

  • Your <div className="relative"> element's width and height are zero, and you try to position your icon around it. You should make the button the reference point instead:

    <script src="https://cdn.tailwindcss.com/3.4.3"></script>
    
    <div class="mt-5 flex items-center justify-center">
      <button type="button" class="relative hover:bg-secondary-50 group flex h-20 w-20 cursor-pointer items-center rounded-md border border-black p-2 transition-colors">
        <div aria-labelledby="notification-tooltip" class="absolute right-2 top-2 h-4 w-4 -m-4 rounded-full bg-red-700"></div>
      </button>
    </div>