Explain Codes LogoExplain Codes Logo

What is the mouse down selector in CSS?

html
pseudo-classes
accessibility
css-frameworks
Anton ShumikhinbyAnton Shumikhin·Aug 6, 2024
TLDR

To style elements during a mouse down event in CSS, use the :active pseudo-class.

Example:

button:active { /* The button turns this when you press it hard */ background-color: blue; }

This ensures a <button> element turns blue on being clicked and held down.

Using :active for interactivity and feedback

The :active pseudo-class can provide visual feedback during interactions. Paired with :hover, elements smoothly transition into a pressed state:

button:hover { /* Mouse hovers and button blushes slightly */ opacity: 0.9; } button:active { /* Button fully committed with a dark blush */ background-color: darkblue; }

Ensure :hover is defined before :active for a naturally cascading effect. Beware of specificity wars, as higher specific selectors or inline styles can override your :active styles.

Combining pseudo-classes

To further amplify the depth of interactive elements, leverage the power of combined pseudo-classes:

input:focus:active { /* The green glow on being touched. Superpowers I tell ya */ box-shadow: 0 0 10px green; }

This creates an extraordinary effect; an input element glows green when focused and pressed at the same time.

Accessibility is key

While fancy aesthetics are great, they shouldn't compromise accessibility. Avoid style changes that could decrease the text contrast ratio below WCAG recommended levels.

Realistic feedback using :active

For 3D-like elements, :active should be used in tandem with transform property:

button { /* Setting up our quick reaction time */ transition: all 0.2s ease; } button:active { /* Giving the button a tiny nudge downwards. Squeeze! */ transform: translateY(2px); }

This provides a feel similar to clicking a real physical button, enhancing the realism of the user interface.

Dealing with CSS libraries

Working with CSS frameworks may lead to conflicts with the default :active styling. Circumvent this by boosting the specificity of your selectors or, as a last resort, using the !important rule.

Think beyond buttons

The use of :active extends beyond just buttons. Be creative – apply :active to icons, card elements, and even custom form elements to explore its full potential!