Home >Web Front-end >CSS Tutorial >What's the Difference Between CSS's :focus and :active Pseudo-Classes?
Distinction Between :focus and :active Pseudo-Classes
Understanding the difference between the :focus and :active states is crucial when working with CSS. These pseudo-classes represent distinct element states that come into play when interacting with HTML elements.
What is :focus?
The :focus state indicates that an element has received input focus. This state is typically triggered when an element receives keyboard input or when the user selects it using other focusable mechanisms. Elements like form elements (:input, :button, :a), frame/:iframe behave this way.
What is :active?
The :active state represents an element that is currently being activated by the user. This state is common in interactive scenarios, such as when a user clicks a button or presses a key. For instance, a button typically enters the :active state when clicked and is released.
How to Differentiate :focus and :active
While seemingly similar when an element is clicked, :focus and :active are distinct states. When a user clicks on an element, it receives both focus and activation, resulting in the :focus:active state. However, these states can be triggered independently. For example, an element can be focused without activation (e.g., using tab) and vice versa.
Example
Consider the following HTML and CSS code:
<style> button { font-weight: normal; color: black; } button:focus { color: red; } button:active { font-weight: bold; } </style> <button> When clicked, my text turns red AND bold!<br /> But not when focused only,<br /> where my text just turns red </button>
When you focus on the button (using tab) without clicking it, the text will only turn red. When you click the button, the text will turn red and bold, indicating that the button is both focused and activated.
The above is the detailed content of What's the Difference Between CSS's :focus and :active Pseudo-Classes?. For more information, please follow other related articles on the PHP Chinese website!