2.1 Pseudo-class :hover
State pseudo-classes let you apply styles to elements based on their interaction with a user or their current state. These pseudo-classes are often used to enhance the user interface by providing visual feedback on user actions.
The pseudo-class :hover
is applied to an element when the user hovers over it with the mouse cursor.
Syntax:
selector:hover {
properties: values;
}
Example:
In this example, a link changes color and adds underline on hover, while a button changes its background and text color.
/* Styling link on hover */
a:hover {
color: red;
text-decoration: underline;
}
/* Styling button on hover */
button:hover {
background-color: #3498db;
color: white;
}
2.2 Pseudo-class :focus
The pseudo-class :focus
is applied to an element when it receives focus, for example, when clicking on a form element or navigating to it using the Tab key.
Syntax:
selector:focus {
properties: values;
}
Example:
In this example, an input field changes its border color and removes outline on focus, and a textarea changes its background color.
/* Styling input on focus */
input:focus {
border-color: blue;
outline: none;
}
/* Styling textarea on focus */
textarea:focus {
background-color: #f0f0f0;
}
2.3 Pseudo-class :active
The pseudo-class :active
is applied to an element at the moment it's activated by the user, such as when a mouse button is pressed. This pseudo-class is often used for creating visual feedback when pressing interface elements.
Syntax:
selector:active {
properties: values;
}
Example:
In this example, a link changes color at the moment of pressing, and a button changes its background color and slightly reduces size, creating a pressing effect.
/* Styling link on press */
a:active {
color: green;
}
/* Styling button on press */
button:active {
background-color: #2980b9;
transform: scale(0.98);
}
2.4 Pseudo-class :visited
The pseudo-class :visited
is applied to links that a user has already visited. It allows styling visited links differently from unvisited ones.
Syntax:
selector:visited {
properties: values;
}
Example
In this example, a visited link changes its color to purple to stand out from unvisited links:
/* Styling visited link */
a:visited {
color: purple;
}
2.5 Combining Pseudo-classes
State pseudo-classes can be combined to create complex interactive styles. For example, you can set different styles for links depending on their state.
Example of Complete Implementation
In this example, link styling changes based on their state: base state, visited links, links on hover, and links on press:
/* Base style for links */
a {
color: blue;
text-decoration: none;
}
/* Styling visited link */
a:visited {
color: purple;
}
/* Styling link on hover */
a:hover {
color: red;
text-decoration: underline;
}
/* Styling link on press */
a:active {
color: green;
}
GO TO FULL VERSION