I have this HTML:
<div class="section">
<div class="header">header</div>
<div class="content">
<div>sub contents 1</div>
<div>sub contents 2</div>
</div>
</div>
I want to access the direct children of div with class "section" which would be divs with class: "header" and "content".
I know with CSS we can do: div.section > div
But how to do this using Tailwind CSS?
There are three options these days.
You could use these simple lines in tailwind.config.js
to give you child
and child-hover
options.
plugins: [
function ({ addVariant }) {
addVariant('child', '& > *');
addVariant('child-hover', '& > *:hover');
}
],
Then use like this
<div class="child:text-gray-200 child-hover:text-blue-500">...</div>
Which will give every child a gray text color, and a blue one on hover.
See here for more information on adding variants using a plugin
Since 4th of July 2022, Tailwind added an ad-hoc approach to target specific elements. You can now use the below without any need for plugins.
<div class="[&>*]:text-gray-200 [&>*:hover]:text-blue-500">...</div>
See the answer of @phum for more info!
Since 19th of December 2023, Tailwind added child selectors! You can now use the below.
<div class="*:text-gray-200 hover:*:text-blue-500">...</div>
See here for the release notes.