I want to style an <a>
tag inside a using Tailwind CSS. I want to add the style via the parent <ul>
tag. I tried [&>li>a]
, but it doesn't work as expected.
Here is my HTML structure:
<ul class="flex items-center [&>li>a]:hover:text-white">
<li class="flex items-center">
<div>
<a href="/"> Route3 </a>
</div>
<a href="/"> Route2 </a>
<span class="hero-chevron-right separator-icon"></span>
</li>
</ul>
How can I achieve this styling correctly? I don't want to change any config or add new selectors.
hover:
modifier to the front. The position of the modifier affects the final selector's effectiveness.<a>
, in CSS you should select li a
instead of li>a
, which only selects direct child elements. But note that in Tailwind you need to use _
instead of spaces.<script src="https://cdn.tailwindcss.com/3.4.5"></script>
<ul class="flex items-center hover:[&>li_a]:text-white">
<li class="flex items-center">
<div>
<a href="/"> Route3 </a>
</div>
<a href="/"> Route2 </a>
<span class="hero-chevron-right separator-icon"></span>
</li>
</ul>
If you're sure that the child element of ul
must be li
, you can simplify the selector even further to: hover:[&_a]:text-white
.