The difference between the :focus and :active selectors
Differences between the :focus and :active Selectors
:focus
selector: It is typically used for form elements or elements that can be focused using the keyboard or mouse, such as input boxes and text areas. When the tab
key is used on a specific element, the element is in focus. The focus state remains the same until the user tabs to another element or clicks.
Syntax:
:focus {
// CSS Property
}
Example: This example illustrates the use of the :focus
selector –
<!DOCTYPE html>
<html>
<head>
<title>Focus pseudo class</title>
<style>
div.one{
margin-left:40%;
margin-top: 10%;
}
h1{
color: green;
font-family: Arial, Helvetica, sans-serif;
letter-spacing: 2px;
}
button{
font-size: x-large;
padding: 10px;
border: 2px solid black;
} button:focus{
color: green;
background-color: white;
font-style: italic;
}
</style>
</head>
<body>
<div class="one">
<h1>GeekDocs GeekDocs</h1>
<button type="submit">
Focus or Click here
</button>
</div>
</body>
</html>
Note: In the example above, the following CSS property is used to set the :focus
selector.
button:focus {
color: green;
background-color: white;
font-style: italic;
}
These CSS properties are used to style the button.
- The text color will change to green.
- The button’s background color will change to white.
- The font style will change from normal to italic.
active: This is commonly used for buttons and anchor tags. It fires when the user clicks the mouse. The active state will remain the same until the user holds down the mouse.
Syntax:
:active {
// CSS property
}
Example: This example illustrates the use of the :active
selector.
<!DOCTYPE html>
<html>
<head>
<title>
:active pseudo class
</title>
<style>
div.one {
margin-left:40%;
margin-top: 10%;
}
h1 {
color: green;
font-family: Arial, Helvetica, sans-serif;
letter-spacing: 2px;
}
button {
font-size: x-large;
padding: 10px;
border: 2px solid black;
}
button:active {
color:white;
background-color: green;
font-family: 'Courier New', Courier, monospace
} </style>
</head>
<body>
<div class="one">
<h1>GeekDocs GeekDocs</h1>
<button type="submit">
Focus or Click here
</button>
</div>
</body>
</html>
Note: In the example above, the following CSS properties are used to set the :active
selector.
button:active {
background-color: green;
font-family: 'Courier New', Courier, monospace
}
With these lines of code, the style of the focus button is changed –
- The button’s background color will be changed to green.
- The font family will be changed.