Search code examples
cssfrontendtailwind-cssmarkdown

How do I apply styles to only the element I'm hovering on using Tailwind Typography and prose?


I'm currently utilizing Tailwind typography and prose to style my markdown pages. I'm attempting to incorporate a hover effect specifically for images. However, I'm encountering an issue where the hover effect is applied to all images simultaneously, rather than just the one the cursor is over. Any suggestions on how to rectify this?

This is my code:

<article
    class="prose-img:w-full prose-img:rounded-2xl prose-img:object-cover prose-img:transition-all prose-img:duration-500 prose-img:ease-out prose-img:hover:scale-[1.01] prose-img:md:rounded-3xl"
>

I've applied a prose-img:hover style, expecting it to only apply to the actual element I'm hovering on. Instead, it will apply it too all images. It also seems to hovering on one image will actually activate all of them.


Solution

  • As per the documentation, sometimes variant order matters:

    Ordering stacked modifiers

    When stacking modifiers, they are applied from the inside-out, like nested function calls:

    // These modifiers:
    'dark:group-hover:focus:opacity-100'
    
    // ...are applied like this:
    dark(groupHover(focus('opacity-100')))
    

    For the most part this doesn’t actually matter, but there are a few situations where the order you use actually generates meaningfully different CSS.

    In your situation, you have prose-img:hover: which is conceptually like prose-img(hover(…)). This would evaulate to:

    1. hover: – hover this element (the <article>).
    2. Select all <img> elements within the prose.

    Whereas really, it seems like you'd want the reverse, hover:prose-img::

    1. Select all <img> elements within the prose.
    2. hover: – hover this element (the <img> element within the prose).

    <script src="https://cdn.tailwindcss.com/3.4.1?plugins=typography"></script>
    
    <article
      class="prose-img:w-full prose-img:rounded-2xl prose-img:object-cover prose-img:transition-all prose-img:duration-500 prose-img:ease-out hover:prose-img:scale-[1.01] prose-img:md:rounded-3xl"
    >
      <img src="https://picsum.photos/500/100">
      <img src="https://picsum.photos/500/100?">
    </article>