The :active
pseudo-class applies styles to an element during the time a user is activating it, such as when a link or button is being clicked.
Example 1: Button Active State
/* Style for a button */
.my-button {
background-color: #28a745;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}
/* Style for the button when it is being clicked */
.my-button:active {
background-color: #218838;
transform: translateY(2px);
}
Explanation
When the button is clicked, its background color darkens, and it moves down slightly, giving the user a sense of pressing the button.
Example 2: Link Active State
/* Style for a link */
.my-link {
color: #dc3545;
transition: color 0.2s ease;
}
/* Change the color of the link when it is being clicked */
.my-link:active {
color: #c82333;
}
Explanation
This code changes the color of a link at the moment it is clicked, providing immediate feedback to the user that their action has been registered.
Example 3: Div Active State
/* Style for a clickable div */
.clickable-div {
padding: 20px;
border: 2px solid #ffc107;
cursor: pointer;
}
/* Change the border color and background when the div is active */
.clickable-div:active {
background-color: #ffc107;
color: white;
}
Explanation
This makes a div
element behave like a button. When clicked, the background and border colors change, indicating an active state.
Example 4: Icon Active State
/* Style for an icon */
.my-icon {
font-size: 24px;
color: #17a2b8;
cursor: pointer;
transition: transform 0.2s ease;
}
/* Scale the icon down when it is active */
.my-icon:active {
transform: scale(0.9);
}
Explanation
When the user clicks on the icon, it scales down slightly. This subtle animation gives the user a tactile sense of interaction with the icon.
Example 5: Input Field Active State
/* Style for an input field */
.my-input {
border: 1px solid #ced4da;
padding: 8px;
}
/* Change the border color of the input field when it is active */
.my-input:active {
border-color: #007bff;
}
Explanation
While a user is clicking and holding down on the input field, the border color will change, indicating that the element is currently being interacted with.