How to Use :active in CSS for Button and Link Interaction
Use the
:active pseudo-class in CSS to style an element when it is being clicked or pressed by the user. It applies styles only during the active interaction, such as when a button or link is held down.Syntax
The :active pseudo-class targets an element during the moment it is being activated by the user, usually by clicking or pressing it.
selector:active— selects the element when active.- Styles inside the block apply only while the element is pressed.
css
button:active {
background-color: #0053ba;
color: white;
}Example
This example shows a button that changes color while you press it. The :active style applies only during the click.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Active Example</title> <style> button { background-color: #008CBA; color: white; border: none; padding: 12px 24px; font-size: 1rem; cursor: pointer; border-radius: 4px; transition: background-color 0.2s ease; } button:active { background-color: #0053ba; } </style> </head> <body> <button>Click Me</button> </body> </html>
Output
A blue button labeled 'Click Me' that darkens to a deeper blue only while pressed.
Common Pitfalls
One common mistake is expecting :active styles to stay after the click ends; it only works while the element is pressed. Another is placing :active styles before :hover in CSS, which can cause unexpected behavior because order matters.
Also, :active does not work on some elements on touch devices unless they are interactive (like buttons or links).
css
/* Wrong order - :hover overrides :active */ button:active { background-color: #0053ba; } button:hover { background-color: #0077cc; } /* Correct order - :active after :hover */ button:hover { background-color: #0077cc; } button:active { background-color: #0053ba; }
Quick Reference
- :active applies styles only while the element is pressed.
- Use it to give visual feedback on clicks or taps.
- Order matters: place
:activestyles after:hoverstyles. - Works best on interactive elements like buttons and links.
Key Takeaways
Use
:active to style elements only while they are being clicked or pressed.Place
:active styles after :hover styles to avoid conflicts.:active works best on interactive elements like buttons and links.The style disappears immediately after releasing the click or tap.
On touch devices,
:active may require the element to be interactive to work.