Categories
Web development

CSS :focus & :focus-within Selectors

CSS :focus and :focus-within selectors

CSS :focus selector

The CSS :focus selector is used to match the element that has focus.

Syntax:

:focus {
  CSS declarations;
} 

Example1:

<!DOCTYPE html>
<html>
<head>
<style>
input:focus {
  background-color: #2a9d8f;
}
</style>
</head>
<body>

<p>Click inside the text fields to change the background to green:</p>

<form>
  Name: <input type="text" name="name"><br>
  Surname: <input type="text" name="surname">
</form>

</body>
</html>

Output:

Click inside the text fields to change the background to green:

Name:
Surname:

Example2:

<!DOCTYPE html>
<html>
<head>
<style>
input[type=text] {
  width: 150px; 
  transition: width .35s;
}
input[type=text]:focus {
  width: 250px;
  background-color: #e9c46a;
}
</style>
</head>
<body>

Example: <input type="text" name="search">

</body>
</html>

Output:

Example:

CSS :focus-within selector

The CSS :focus-within selector matches an element if that element contains any children that have :focus.

Example:

<!DOCTYPE html>
<html>
<head>
<style>

form {
  border: 2px solid #333;
  padding: 25px;
  transition: background 0.35s;
  width:30%;
  text-align: center;
}
form:focus-within {
  background-color: #e9c46a;
}
</style>
</head>
<body>

<form>
  <label for="name">First name</label>
  <input type="text" name="name" />
  </br>
   <label for="surname">Last name</label>
  <input type="text" name="surname" />
</form>

</body>
</html>

Output:


Enjoy coding!

Read also:

CSS :valid & :invalid Selectors

CSS :first-of-type Selector

CSS :hover and :active selectors