CSS for Web Development

0% completed

Previous
Next
Common states (hover, active, focus)

Pseudo-classes let you style elements based on their state. With pseudo-classes, you can change the style of an element when the user interacts with it. In this lesson, we use pseudo-classes such as :hover, :active, and :focus to add interactivity without using JavaScript.

  • :hover: Applies styles when a user moves the mouse over an element.
  • :active: Applies styles when an element is being clicked.
  • :focus: Applies styles when an element is focused (for example, when a user clicks on an input field or navigates to a link using the keyboard).

Syntax

Follow the code block below to use common pseudo-classes:

selector:hover { /* Styles for when the element is hovered */ } selector:active { /* Styles for when the element is clicked */ } selector:focus { /* Styles for when the element is focused */ }

Explanation:

  • The :hover pseudo-class is used to change the style when the mouse pointer is over an element.
  • The :active pseudo-class changes the style during the moment an element is being clicked.
  • The :focus pseudo-class is used to style elements when they have focus, for instance, when a text input is selected.

Example 1: Hover on a Button

In this example, the background of a button changes when the mouse hovers over it.

HTML

. . . .

Explanation:

  • Button Default:
    • The button starts with a green background and white text.
  • On Hover:
    • When the mouse hovers over the button, the background color changes to a slightly darker green.
  • Outcome:
    • The effect provides visual feedback that the button is active and clickable.

Example 2: Active State on a Link

In this example, a link changes its color when clicked. The active state gives a quick visual cue when the user presses the link.

HTML

. . . .

Explanation:

  • Default Link Style:
    • The link is blue and does not have an underline.
  • On Active:
    • When the link is clicked, its color changes to a darker blue.
  • Outcome:
    • The change in color provides immediate feedback, showing the user that the link is being activated.

Example 3: Focus on an Input Field

In this example, an input field gets a border when it receives focus. This helps users see which field is active for typing.

HTML

. . . .

Explanation:

  • Default Input Style:
    • The input field has a light grey border.
  • On Focus:
    • When the user clicks on the input, its border color changes to orange.
  • Outcome:
    • This visual change makes it clear which input field is active, improving usability and navigation.

These examples show how pseudo-classes like :hover, :active, and :focus add interactive effects to elements. They are simple yet powerful tools to enhance user experience without requiring extra scripts.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next