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?

0

2 Answers 2

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/

2
  • 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" ? Commented Jul 30, 2013 at 21:12
  • 1
    sure, just add the class as an argument to the .parent() selector, like $(this).parent('input-append').addClass('active');
    – braican
    Commented Jul 30, 2013 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.

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