44

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>
4
  • Nope: en.wikipedia.org/wiki/Cascading_Style_Sheets#Limitations (2nd bullet point) Commented Feb 6, 2010 at 9: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. Commented Feb 9, 2010 at 4: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
    Commented Mar 22, 2017 at 6: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 Commented Nov 17, 2017 at 19:47

2 Answers 2

31

You can use has():

div:has(input:focus), 
div:has(a:focus) {
    background: pink;
}

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

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

1
9

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!

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.