Creating Visually Engaging User Experiences with : focus and :focus-within
Table of contents
As I was working on my personal portfolio website over the weekend, I thought about a feature that I wanted to implement. I wanted to create a visually engaging user experience by making the labels of the input fields responsive to user interactions.
After some research, I discovered that these powerful CSS pseudo-selectors :focus and :focus-within can be used to implement it.
In this article, I will be sharing my findings and demonstrating how you can use these selectors to enhance the functionality of your forms and create dynamic user interfaces.
The CSS pseudo-selector :focus
The CSS pseudo-selector: focus is used to select elements that currently have focus, such as an input field that a user is typing in or a button that a user has clicked on. This can be useful for styling elements when they are actively being used by a user.
For example, you can use :focus to change the color of a button when it is clicked on, like this:
button:focus {
color: blue
}
The image below shows the look before any interaction with the button.
When the button is clicked, the font color of the button changes to blue and remains that way until it is no longer in focus.
The pseudo-selector :focus-within
Another powerful css pseudo-selector is :focus-within. This selector allows you to select an element when any of its descendants have focus. This can be useful for styling a container element when one of its children has focus.
For example, you can use :focus-within to change the background color of a form when any of its input fields are selected, like this:
.contact__form:focus-within {
background-color: yellow;
}
When the form field is engaged, it shows a yellow background color.
Both :focus and :focus-within can be used to create interactive and visually engaging user interfaces, and they are just a couple of examples of the many powerful CSS selectors available for styling HTML elements.
It's important to note that :focus-within is not supported in some older browser like IE 11, so you can use javascript to achieve the same effect, as I did in my project.
CSS is a powerful tool for styling and layout of web pages and it can be used to create visually appealing and interactive user interfaces. With the use of pseudo-selectors such as :focus and :focus-within, you can create dynamic and engaging user interfaces.
I will be sharing my knowledge and insights on frontend engineering through articles and will soon share the code for my portfolio website on GitHub. Follow me to stay updated.