I’m working on a toggle, this is my code:
import style from "./Toggle.module.scss";
export default function Toggle() {
return (
<>
<input type="checkbox" id="toggle" className={style.toggle} />
<label htmlFor="toggle" className={style.label} />
</>
);
}
.toggle {
height: 0;
width: 0;
opacity: 0;
}
.label {
width:60px;
height: 30px;
border-radius:30px;
display: block;
background-color: #ebebeb;
box-shadow: 1px 2px 5px 1px rgba(0,0,0,0.2) inset;
left:10px;
padding-left: 5px;
position: relative;
&::after {
content: '';
position: absolute;
width: 23px;
height: 23px;
border-radius: 50px;
background-color: green;
top: 50%;
transform: translateY(-50%);
transition: 0.3s;
}
}
.toggle:checked ~ .label::after{
transform: translateX(32px);
}
initially the knob is perfectly centered inside the switch, but when i click it, it makes a diagonal movement instead of moving in a straight line to the right. See codesandbox for details.
https://codesandbox.io/p/sandbox/red-microservice-gq48pj?file=%2Fsrc%2Findex.js
2
Answers
You need to add the
translateY: -50%
to the toggled transformation as well if you don’t that value will not be added to the transformation:One solution is:
notice the translateX from translateY, since you’re moving horizontally you don’t need to set the Y axis at all.