4

I know I can set a style on the focused input element like this:

input:focus
{ 
  background-color:yellow;
}

But is it somehow possible to set a style on a parent element when an input has focus? e.g.

<div class="foo">
      <input type="text />
      Hello
</div>

Can I affect the "foo" style when the input has focus here?

edit: Possible duplicate of Affecting parent element of :focus'd element (pure CSS+HTML preferred)

However, can someone explain how that works?

Community
  • 1
  • 1
Roger Johansson
  • 22,764
  • 18
  • 97
  • 193

2 Answers2

5

There is no parent selector in css (yet). http://css-tricks.com/parent-selectors-in-css/

You can, however, select it with jQuery:

html

<div class="parent">
    <input type="text" />
</div>

css

.parent {
    /* parent styles */
}
.parent.active {
    /* do stuff when the input is hovered */
}

js

// listen for a focus event on the input,
//  and then add a class to the parent
$('input').on('focus', function () {
    $(this).parent().addClass('active');
});

http://jsfiddle.net/M64nv/

braican
  • 2,172
  • 1
  • 18
  • 16
  • Awesome, is there a way to only appy the class to the parent if the parent already contains a specific class? e.g. if parent has class "input-append" and/or "input-prepend" ? – Roger Johansson Jul 30 '13 at 21:12
  • 1
    sure, just add the class as an argument to the .parent() selector, like $(this).parent('input-append').addClass('active'); – braican Jul 30 '13 at 21:14
1

No. There is no parent selector in CSS, so you cannot trigger style rules on a parent element when one of its descendants is hovered (or based on any child element conditions). You need to use Javascript for this.

Ennui
  • 10,102
  • 3
  • 35
  • 42