Can I have an onclick effect in CSS?
In CSS, simulate an onclick effect with the :active
pseudo-class for instant visual feedback or use a :checked
pseudo-class with a hidden checkbox to create a more durable toggle effect.
Instant click with :active
:
Toggle effect with :checkbox
:
These snippets use pure CSS to make your UI responsive to user clicks.
The Checkbox Hack
To make a persistent state, use the CSS checkbox hack. It uses a hidden checkbox to store state and a label
that acts like a button to change states.
Button-like labels
Labels can be styled like buttons with properties like background
, border-radius
, and box-shadow
:
Adding effects to active states
Enhance interaction by adding effects to :active
and :focus
states:
Simulate resizing clickable elements by manipulating width
and height
when :checked
:
Adding keyboard navigation
To enhance accessibility, use tabindex
to allow non-button elements to receive focus:
:target Pseudo-class
The :target
pseudo-class can highlight navigational elements and toggle content visibility:
Use :target
to highlight the current section in navigation menus:
Remember, :target
operation is built on URL mechanics, so it impacts page jumps and back button behavior.
Was this article helpful?