Enhancing Form Interactivity with CSS Focus-Within

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the :focus-within pseudo-class in CSS, which allows us to apply styles to a parent element when any of its child elements are focused. We will use this feature to create a visually appealing form that changes its appearance when the user interacts with it. Through this lab, you will gain a better understanding of how to enhance the user experience by using CSS to create interactive forms.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Focus Within

index.html and style.css have already been provided in the VM.

To change the appearance of a form when any of its child elements are focused, use the pseudo-class :focus-within to apply styles to the parent element. For example, in the given HTML code, if any of the input fields are focused, the form element will have a green background. To apply styles to the child elements, use appropriate CSS selectors like label and input.

<form>
  <label for="username">Username:</label>
  <input id="username" type="text" />
  <br />
  <label for="password">Password:</label>
  <input id="password" type="text" />
</form>
form {
  border: 2px solid #52b882;
  padding: 8px;
  border-radius: 2px;
}

form:focus-within {
  background: #7cf0bd;
}

label {
  display: inline-block;
  width: 72px;
}

input {
  margin: 4px 12px;
}

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Focus Within lab. You can practice more labs in LabEx to improve your skills.