:focus
- The
:focuspseudo-class is applied when the user clicks or navigates using the keyboard (e.g., Tab key) to focus on an element. It is commonly used for form inputs such as<input>and<textarea>, where the:focusstate is activated upon gaining focus. - For example, when the user clicks on an input field and prepares to type text, the input field is in the
:focusstate. - The
:focusstate is typically used to enhance accessibility and user experience by changing the element's style to indicate the currently interactive element. - CSS code example:
This code means that when the input field gains focus, its border becomes 2 pixels wide and blue.cssinput:focus { border: 2px solid blue; }
:active
- The
:activepseudo-class is applied when the user clicks an element and the mouse button is pressed. It indicates that the element is being activated during the click. - For example, when the user clicks a button, during the time the mouse button is pressed, the button is in the
:activestate. - Unlike
:focus, the:activestate is typically very brief, existing only during the interaction. - CSS code example:
This code means that when the button is clicked, its background color changes to red.cssbutton:active { background-color: red; }
Example Usage Scenarios
Suppose you have a submit button for a form. When the user navigates to the button using the keyboard and prepares to click it, the button may display an outline or shadow to indicate it has focus (:focus). When the user actually clicks the button and holds it down (before releasing the mouse button), the button's color may change or it may appear pressed, indicating it is active (:active).
These states can be combined to provide visual feedback and enhance the user interface's interactivity. For example, a button might define both :focus and :active pseudo-classes:
cssbutton:focus { outline: none; box-shadow: 0 0 5px rgba(81, 203, 238, 1); } button:active { transform: translateY(2px); }
In this example, when the button gains focus, it displays a blue glow as an outline, and when the button is activated or clicked, it moves down by 2 pixels, giving the user a visual effect of pressing.