Home > Software engineering >  Tailwind toggle input
Tailwind toggle input

Time:01-19

I have the following toggle input which comes from:

<div className="relative">
  <input
    data-testid="toggle-input-checkbox"
    onChange={handleOnChange}
    id={id}
    type="checkbox"
    className="sr-only"
    checked={isChecked}
  />

  <div className="base w-9 h-3.5 bg-grey-6 rounded-full shadow-inner" />

  <div className="dot bg-white absolute w-5 h-5 rounded-full shadow -left-1 -top-1 transition" />
</div>

and toggle.css:

input:checked ~ .base {
  background-color: #46e18c;
}

input:checked ~ .dot {
  transform: translateX(100%);
}

is there a way in Tailwind to avoid using custom classes to achieve the desired style?

CodePudding user response:

Use peer modifier, like that:

  // Add `peer` to the element which state you want to track
  <input type="checkbox" checked  />

  // Then use `peer-*` modifiers on the target element which style you want to change
  <div >Sibling</div>

Playground link

More info in the docs as always

  •  Tags:  
  • Related