{"id":256635,"date":"2017-07-29T07:40:44","date_gmt":"2017-07-29T14:40:44","guid":{"rendered":"http:\/\/css-tricks.com\/?page_id=256635"},"modified":"2021-09-15T20:52:47","modified_gmt":"2021-09-16T03:52:47","slug":"focus-within","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/almanac\/selectors\/f\/focus-within\/","title":{"rendered":":focus-within"},"content":{"rendered":"\n

The :focus-within<\/code> pseudo-selector in CSS is a bit unusual, although well-named and rather intuitive. It selects an element if that element contains any children that have :focus<\/code>.<\/p>\n\n\n\n

form:focus-within {\n  background: lightyellow;\n}<\/code><\/pre>\n\n\n\n

Which works like this…<\/p>\n\n\n\n

<!-- this form will be selected -->\n<form action=\"#\">\n\n  <!-- when this input is in focus -->\n  <input type=\"text\">\n\n<\/form><\/code><\/pre>\n\n\n\n\n\n\n\n

I said “unusual” because it’s not common in CSS to be able to select a parent element based on the existence or state of child elements. Sure is useful though!<\/p>\n\n\n\n

Here’s an example form to try it on:<\/p>\n\n\n\n