CSS :active
The CSS :active pseudo-class applies styles to an element at the moment it is being activated. For example, when a user clicks on a link or a button, the styles defined using the :active
pseudo-class will apply for the duration of the interaction.
The syntax for the :active
pseudo-class is:
selector:active {
property: value;
}
Where:
Parameter | Description |
---|---|
selector | The HTML element to which the active effect will be applied. |
property | The CSS property to be changed when the element is active. |
value | The value assigned to the CSS property during the active state. |
Examples
1. Changing Link Color When Clicked
In this example, the text color of a link (<a>
) changes to red while it is being clicked.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
a:active {
color: red;
}
</style>
</head>
<body>
<a href="#">Click me</a>
</body>
</html>
2. Changing Button Background on Active
In this example, the background color of a button changes to green while it is being clicked.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
button:active {
background-color: green;
color: white;
}
</style>
</head>
<body>
<button>Click me</button>
</body>
</html>
3. Shrinking a Button on Active
In this example, the button shrinks slightly to provide a press-down effect when it is clicked.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
button:active {
transform: scale(0.95);
transition: transform 0.2s;
}
</style>
</head>
<body>
<button>Click me</button>
</body>
</html>
4. Changing Background of Div on Active
In this example, the background color of a <div>
changes to lightgrey when it is clicked.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div:active {
background-color: lightgrey;
}
</style>
</head>
<body>
<div style="width: 200px; height: 100px; border: 1px solid black;">
Click me!
</div>
</body>
</html>
5. Rotating an Icon on Active
Here, an icon rotates 45 degrees when it is clicked.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha512-Evv84Mr4kqVGRNSgIGL/F/aIDqQb7xQ2vcrdIwxfjThSH8CSR7PBEakCr51Ck+w+/U6swU2Im1vVX0SVk9ABhg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
i:active {
transform: rotate(45deg);
transition: transform 0.3s;
}
</style>
</head>
<body>
<i class="fas fa-arrow-right" style="font-size: 24px;"></i>
</body>
</html>