37

How can I change the background of a parent <div> when an <input> or <a> is :focus'd (or any other dynamic pseudo-class?

Eg

<div id="formspace">
<form>
<label for="question">
How do I select #formspace for the case when a child is active?</label>
<input type="text" id="question" name="answer"/></form></div>
Shane Daniel
  • 889
  • 1
  • 7
  • 14
  • Nope: http://en.wikipedia.org/wiki/Cascading_Style_Sheets#Limitations (2nd bullet point) – Crescent Fresh Feb 06 '10 at 09:05
  • Thanks all. Just checking since I couldn't seem to come up with any way with pure CSS and html tag movement. I knew javascript could do it; just wanted to keep my hands clean. – Shane Daniel Feb 09 '10 at 04:25
  • 1
    I don't think this question should be considered duplicated to that one. This question is just asking a particular situation but not general question about parent selector. And there _MAY_ be some solution for this situation but not general one, although the general one do _NOT_ have a _solution_. – tsh Mar 22 '17 at 06:49
  • 4
    The linked question is not a proper duplicate of this question because it does not mention `:focus` -- only parent selectors. There is a new `:focus-within` pseudo selector with some browser support which would satisfy the OP's question here but would not correctly answer the linked "duplicate" question. Can we have this question unmarked as a duplicate or have a more accurate duplicate question linked? @Paulie_D @kapa – Keegan Brown Nov 17 '17 at 19:47

2 Answers2

27

Unfortunately css doesn't support parent selectors. :(
So the only way to do it is to use javascript like the jQuery parent method.

Update: CSS Selectors Level 4 will support parent selectors! http://www.w3.org/TR/selectors4/#subject

Rowno
  • 2,914
  • 1
  • 20
  • 14
6

The only way I can think of is with JavaSCript:

function focusLink(isOnFocus)
{
    if (isOnFocus)
      document.getElementById('formspace').className = "<make a focus class name here>";
    else
      document.getElementById('formspace').className = "<default class name here>";
}

...

<input onFocus="focusLink(true)" onBlur="focusLink(false)">

Hope that helps!

anthares
  • 10,337
  • 3
  • 39
  • 58