1

I have this simple example :

<html>
<head>
<style>
:root {
    --textbox-box-shadow: none;
}
.example3 {
    display: block;
    border: 1px solid red;
    padding: 10px;
    box-shadow: var(--textbox-box-shadow);
}


.example3 input:focus {
    --textbox-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px red;
}
</style>
</head>
<body>

<div class="example3">
Enter your name : <input>
</div>

</body>
</html>

I'm trying to make the 'div' glow when the input element inside it is focused.

The code doesn't work and I can't figure out why.

Btw when giving the variable an initial value of inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px red; instead of "none", the div does glow red.

How can I fix it ?

Example can be found here

Edit:

Turns out that this actually creates a new local variable by the name "textbox-box-shadow".

.example3 input:focus {
    --textbox-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px red;
}

Still the question stands, how can I make the outer div <div class="example3"> glow when input is focused with pure CSS and without using javascript (if that's possible)?

Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
Wolf359
  • 2,620
  • 4
  • 42
  • 62

2 Answers2

2

The new CSS pseudo-class :focus-within would be your best shot to achieve this.

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

:root {
  --textbox-box-shadow: none;
}

.example3 {
  display: block;
  border: 1px solid red;
  padding: 10px;
  box-shadow: var(--textbox-box-shadow);
}

.example3:focus-within {
  --textbox-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px red;
}
<div class="example3">
  Enter your name : <input class="ip">
</div>
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
-1

You're on the right track. You need to declare your CSS variable as a value, and then pass that variable as a value for different properties. I.e.:

:root {
     --textbox-box-shadow: none;
     --textbox-box-shadow-glow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px red;
}
.example3 {
    display: block;
    border: 1px solid red;
    padding: 10px;
    box-shadow: var(--textbox-box-shadow);
}
.example3 input:focus {
    box-shadow: var(--textbox-box-shadow-glow);
}
benjamyan
  • 210
  • 1
  • 10
  • You misunderstood the question: I want the outer Div (example3) to glow, not the input element itself. Is that possible without using js ? – Wolf359 Aug 18 '19 at 04:19