0
0
CSSmarkup~5 mins

Active and focus states in CSS

Choose your learning style9 modes available
Introduction

Active and focus states help users see which element they are clicking or typing on. This makes websites easier and safer to use.

When you want to show a button is being clicked.
When a user tabs through links or form fields using the keyboard.
To improve accessibility for people who rely on keyboard navigation.
To give visual feedback that an element is ready for interaction.
When designing interactive elements like buttons, links, or inputs.
Syntax
CSS
selector:active {
  /* styles when element is clicked */
}

selector:focus {
  /* styles when element is focused (clicked or keyboard) */
}
:active applies only while the mouse button is pressed down on the element.
:focus applies when the element is selected, either by clicking or keyboard navigation.
Examples
This changes the button color while it is being clicked.
CSS
button:active {
  background-color: darkblue;
  color: white;
}
This highlights the input box when it is selected for typing.
CSS
input:focus {
  border-color: green;
  outline: 2px solid green;
}
This shows a dashed outline around links when focused by keyboard.
CSS
a:focus {
  outline: 3px dashed orange;
}
Sample Program

This page shows a button that changes color while clicked and shows an orange outline when focused by keyboard or mouse.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Active and Focus States Example</title>
<style>
  button {
    padding: 1rem 2rem;
    font-size: 1.25rem;
    background-color: lightblue;
    border: 2px solid blue;
    border-radius: 0.5rem;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  button:active {
    background-color: darkblue;
    color: white;
  }
  button:focus {
    outline: 3px solid orange;
    outline-offset: 3px;
  }
</style>
</head>
<body>
  <main>
    <h1>Active and Focus States Demo</h1>
    <p>Try clicking or tabbing to the button below.</p>
    <button>Click or Tab to me</button>
  </main>
</body>
</html>
OutputSuccess
Important Notes

Always provide visible focus styles for keyboard users to improve accessibility.

Active state only lasts while the mouse button is pressed down.

Use transitions to make state changes smooth and pleasant.

Summary

Active state shows when an element is being clicked.

Focus state shows when an element is selected by keyboard or mouse.

Both states improve user experience and accessibility.