Home > front end >  Using CSS change the background of the form only when one of the children receives the focus [duplic
Using CSS change the background of the form only when one of the children receives the focus [duplic

Time:09-17

I am trying concepts of CSS selectors and want to change the background color of the form to lightblue only when one of the children receives the focus. I want to done this using CSS only. I don't want any type of JavaScript. Here the code :

*, ::before, ::after {
    box-sizing: border-box;
    padding: 0;
}
body {
    background: #f1f1f1;
    font-family: Arial, Helvetica, sans-serif;
    padding: 50px;
    color: #333;
}
form{
width:400px;
padding: 20px;
background-color:red;
margin:20px;
}
.label, .input {
    display: block;
}
label {
    margin-bottom: 3px;
}
input {
    display: block;
    padding: 5px;
    min-width: 350px;
    margin-bottom: 10px;
    border-radius: 3px;
    border: 1px solid rgb(116, 116, 116);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Selectors</title>
  </head>
  <body>
    <form>
      <h3>Express your tastes</h3>
      <label>Your favorite dish</label>
      <input type="text" />
      <label>Your favorite dessert</label>
      <input type="text" />
      <label>Your favorite pastry</label>
      <input type="text" />
    </form>
  </body>
</html>

CodePudding user response:

You may want to use :focus-within pseudo-class. For your example, you have to add:

form:focus-within {
   background-color: lightblue;
}

More you can read about this selector here

CodePudding user response:

You can use CSS pseudo-class :focus-within

defn:

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

Wroking Example

  • Related