GORAGOD.com

Highlighting Label When Input Gets Focus Using CSS

In web development, form design plays a crucial role in providing a seamless user experience. Highlighting the label when an input field is focused is a subtle yet effective way to guide users and make forms more interactive.

In this article, we'll explore how to use the CSS pseudo-class :focus-within to highlight a label when its associated input is focused. This method uses pure CSS, eliminating the need for JavaScript, resulting in cleaner and more efficient code.

How :focus-within Works

The :focus-within CSS pseudo-class is applied when any element inside a container (in this case, the label) receives focus. In the following example, the label's background color changes when the user clicks or focuses on the input field.

<label>
  Username:
  <input type="text" name="username">
</label>

CSS

label {
  background-color: #f0f0f0;
  padding: 5px;
  display: inline-block;
}
label:focus-within {
  background-color: #cce5ff;
  border: 1px solid #66afe9;
}

Code Explanation

  • label: Basic label styling with a light grey background.
  • label:focus-within: When the input inside the label receives focus, the label's background changes to a light blue, and a border is added for emphasis.

Applying :focus-within in Other Cases

This technique can be easily extended to other input types, such as passwords or textareas

<label>
  รหัสผ่าน:
  <input type="password" name="password">
</label>

CSS

label {
  background-color: #ffffff;
  padding: 5px;
  display: inline-block;
  transition: background-color 0.3s;
}
label:focus-within {
  background-color: #ffe6e6; /* เปลี่ยนสีพื้นหลังเป็นสีชมพูเมื่อ Input ถูกโฟกัส */
}

Benefits of Using :focus-within

  1. Enhances user experience (UX) by visually indicating which field is currently in use.
  2. Pure CSS implementation, no need for JavaScript, making the code cleaner and more resource-efficient.
  3. Makes forms more interactive and user-friendly by providing subtle feedback.