Search code examples
javascripthtmlcsspseudo-class

In HTML & CSS can I change the background of a parent DIV when focused on a textbox?


I have read about not being able to change the parent in CSS using pseudo classes such as :focus, so I am here to see if I am doing something wrong or if there is a javascript alternative.

I'd prefer not to use javascript at all though, if possible.

Here is my current code:

.box:focus .test{
background: #00FF00;
} 

So that code should change the background of the DIV .test to green when I click inside the textbox .box.

However this dosen't work, please could someone point me in the right direction, thanks.

Here is a code snippet of my HTML, this is a test page so I can see how this works.

<input name="textfield" type="text" class="box" id="textfield" />

<div class="test" id="test">Content for  id "test" Goes Here</div>

Solution

  • This is actualy possible without using javascript. There is indeed no way to select a parent, but you can select a sibling using css. I set up a small example here: http://jsfiddle.net/k2dAp/1/

    HTML

    <div class='container'>
    <input type='text' />
    <div class='background'></div>
    </div>
    

    CSS

    .container {
      border: red solid 1px; 
      position: relative;    
    }
    .background {
      position: absolute;
      background: grey;
      width: 100%;
      height: 100%;
      z-index: -1;
      top: 0;
      left: 0;   
    }
    input {
      margin: 10px;   
    }
    input:focus + .background {
      background: green;   
    }
    

    As you can see i added an extra div that will act as the background by adding absolute positioning and z-index. Then you can access it with the + selector. This will not be compatible with the old versions of IE but should work fine in modern browsers and degrade garcefully. Adding js will probably work in more browsers, but offcourse not for people with js disabled.