I want to make a focused button lose its focus after being clicked again. To illustrate, I want to click at the red button and it will become blue, then click again on it and it become red again.
import styled from "styled-components";
const Button = styled.button`
width: 200px;
height: 100px;
background-color: red;
&:focus {
background-color: blue;
}
`;
export default function ButtonFocus() {
return <Button>Button</Button>;
}
I know how to make it with javascript, but i’m triyng to make it using just css (styled component in that case, just to keep it on the same page).
2
Answers
you can try below code
Yes, you can achieve this effect.
You’ll need to include two
:focus
-able child elements within the<button>
.Think about the following:
tabindex="0"
you can make any element:focus
-able.pointer-events: none
you can make any element unresponsive to clicks (and, thus, unable to receive focus from user-interaction)opacity: 0
you can render any element invisible (or completely transparent, at any rate)Consequently, if you give your
<button>
two:focusable
<div>
child-elements, you can, via CSS, alternate each<div>
between the two following states:opacity: 1
) but unresponsive to clicks (pointer-events: none
)pointer-events: auto
) but invisible (opacity: 0
)Working Example: