Anjan Dutta

Change parent element property on focus of child in CSS

Change parent element property on focus of child in CSS

We can do it using the CSS pseudo class :focus-within.

.parent:focus-within {
background-color: green;
}

The :focus-within pseudo-class matches elements that either themselves match :focus or that have descendants which match :focus.

Example

Working code below.

The HTML

<html>
<head>
<title>Focus within</title>
</head>
<body>
<div class="parent">
<input class="child" type="text" />
</div>
Checkout my <a href="https://anjandutta.com">blog</a> for more tutorial.
</body>
</html>

The CSS

.parent {
height: 200px;
width: 200px;
border: 1px solid red;
display: flex;
}
.child {
width: 100px;
border: 1px solid green;
margin: auto;
}
.parent:focus-within {
background-color: green;
}