Explain Codes LogoExplain Codes Logo

Can I have an onclick effect in CSS?

html
responsive-design
css-hacks
accessibility
Alex KataevbyAlex Kataev·Oct 19, 2024
TLDR

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:

.btn:active { /* The color blue when the button is clicked. Magic! */ background: blue; }

Toggle effect with :checkbox:

<input type="checkbox" id="tgl" hidden> <label for="tgl" class="btn">Toggle</label>
.btn { /* Default color. Nothing fancy, just grey */ background: grey; } /* Checkbox is checked? We're going blue, baby! */ #tgl:checked + .btn { background: blue; }

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:

.btn { /* It's a button, but it's actually a label. Surprise! */ display: inline-block; padding: 10px 20px; cursor: pointer; background: grey; border-radius: 5px; box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2); } #tgl:checked + .btn { /* Blue steel? Nah, just blue. */ background: blue; box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2); }

Adding effects to active states

Enhance interaction by adding effects to :active and :focus states:

.btn:active { /* Button pressed; will it pop back? Only one way to find out! */ transform: translateY(2px); box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.2); } .btn:focus { /* Who needs a blue light filter when you have a lightblue button? */ outline: none; background: lightblue; }

Simulate resizing clickable elements by manipulating width and height when :checked:

#tgl:checked + .btn { /* Are we in Wonderland? The button is growing! */ width: 200px; height: 60px; }

Adding keyboard navigation

To enhance accessibility, use tabindex to allow non-button elements to receive focus:

<div tabindex="0">Focusable element, keyboard users rejoice!</div>

:target Pseudo-class

The :target pseudo-class can highlight navigational elements and toggle content visibility:

<style> #section:target { /* Warning: approaching the yellow section! */ background: yellow; } </style> <a href="#section">Jump to Section</a> <div id="section"> /* Caution: highlighted content below! */ This section is highlighted when targeted. </div>

Use :target to highlight the current section in navigation menus:

nav a:target { /* The blue frame of fame! */ outline: solid blue 2px; }

Remember, :target operation is built on URL mechanics, so it impacts page jumps and back button behavior.