Selecting parent elements based on the existence or state of child elements has always been a difficult task in CSS. But, the :focus-within
pseudo selector lets us do just that.
The :focus-within
pseudo selector lets us apply focus styles to an element which contains focusable child elements, whenever those child elements are in focus. Examples of focusable elements are [inputs], [selects], [buttons], [textarea] and [a].
A scenario where this could be useful is when you have an input and button grouped like so:
Let’s assume that below is the enabling code:
Since both the input and search buttons are functioning as one unit in this instance, It would be a bad design to focus only on the input when a user clicks on it.
To rectify, we’ll disable the default browser outline focus style for the input and button, and then apply focus on the parent element, which is the input wrapper.
.input-wrapper input:focus,
.input-wrapper button:focus {
outline: 0;
}
.input-wrapper:focus-within {
box-shadow: 0px 0px 10px 0px black;
transition: box-shadow 250ms ease-in;
}
For a full demo, see codepen.
Blog Credits: Linda Ikechukwu
Comments are closed.