I want to add the add a border to my checkbox container when the checkbox is checked.
Currently, I have this:
<label
htmlFor="choose-me"
className=
'flex w-fit items-center justify-evely p-3 border-2 border-grey-4 text-grey-8
peer-checked:bg-light-indigo peer-checked:text-medium-indigo peer-checked:border-medium-indigo'>
<input type="checkbox" id="choose-me" className="peer mr-3 " />
Check me
</label>
I want something like the below:
However, I am unable to change the label styles when I put my input inside the label.
3
Answers
use useState for handle active state:
in JSX:
First off, it’s important to remember that the
peer
functionality in tailwind doesn’t target parents (which is what you currently have). You can only target elements that are next to one another.Additionally, because of how the CSS
:peer
combinator works you can only target previous components, meaning the checkbox MUST come before the peer who’s state you want to affect when the checkbox is checked.Here’s an example that works using pure tailwind/css, assuming you don’t want to handle the state in your react component, as per @Vikesir’s comment (though that was my first thought as well and it’s a good idea).
You’ll notice I’m fudging in an empty div and using that to simulate the background and border changing. I also wrapped the label text in a span to make sure I could change it’s z-index so that both the checkbox and the text were visible above the div that handles the state change.
EDIT:
Here is a version using a pseudo-element built off of the span holding the label text if you don’t want the empty
div
in your code:A CSS-only solution would be to use the
:has
pseudo-selector (note: not supported yet in Firefox). This would apply the classes only if the label wraps a checkbox which has been checked.index.css
Your JSX: (with the unused classes stripped out)
You can test it here: https://play.tailwindcss.com/zidP4zm2Pq
The list of browsers supporting
:has
: https://developer.mozilla.org/en-US/docs/Web/CSS/:has#browser_compatibility