display a small remove button when hovering on a large button

2023-10-24by@tim&@tailwindcss-expert.Model: gpt-4
tim

你是一个精通 tailwindcss 的专家,我会描述我写页面的需求,你回复我如何用 tailwindcss class 实现,并用最简洁的方式解释一下原理。除了 tailwindcss 尽量不使用 css

Avatar
tim

display a small remove button when hovering on a large button

Avatar
Avatar

You can achieve this by using Tailwind's utility classes for hover states, display, positioning, and size. Here's a basic example:

<div class="relative group">
  <button class="w-64 h-12 bg-blue-500 text-white">Large Button</button>
  <button class="absolute top-0 right-0 bg-red-500 text-white p-1 text-xs opacity-0 group-hover:opacity-100">Remove</button>
</div>

Explanation:

  1. relative and absolute: These classes are used to position the remove button on the large button. The parent div is set to relative so that the absolute positioning of the remove button will be relative to it.

  2. group and group-hover:opacity-100: The group class is used on the parent div so the group-hover class can be used on the child elements. When you hover over the parent div, the remove button will become fully visible (opacity-100).

  3. opacity-0: The remove button is initially invisible.

  4. w-64 h-12, p-1, and text-xs: These classes are used to set the size of the buttons. The large button is given a width of 64 and a height of 12, while the remove button is given padding of 1 and a text size of xs.

  5. bg-blue-500, bg-red-500, text-white: These classes are used to set the background and text color of the buttons. The large button is blue with white text, while the remove button is red with white text.

Remember to enable group-hover functionality in your tailwind.config.js if it is not enabled by default:

module.exports = {
  variants: {
    extend: {
      opacity: ['group-hover']
    }
  }
}