9

Is it possible to trigger a parent's class when on hover? I know it can be done with jquery but I want to do a pure css solution.

My code:

.navbar-form{
    padding-left: 55px;
    .input-group{
        width: 200px;
        .form-control{
            border-right: none;
            width: 350px;
             &:hover & {
                border-color: blue;
            }
        }
        .input-group-addon{
            background-color: white;
            border-left: none;
        }
    }
}

FIDDLE: http://jsfiddle.net/fcKyc/

Looking to have that when I focus on the input, .input-group-addon would do something. input and the icon are children of the input-group.

Richard Shi
  • 625
  • 1
  • 9
  • 21
Mohamed El Mahallawy
  • 13,024
  • 13
  • 52
  • 84

2 Answers2

11

If I understand it right, here is my interpretation of the DOM interaction you're describing.

.parent

  • .child1

  • .child2

A hover on .child1 affects .child2

If yeah, then here:

.form-control {
    ... //your CSS for this
    input {
        //CSS for input
        &:hover ~ .input-group-addon {
            //CSS for .input-group-addon when input is hovered
        }
    }
}

OR, if .input-group-addon is right after input (adjacent sibling), then you could use the following:

.form-control {
    ... //your CSS for this
    input {
        //CSS for input
        &:hover + .input-group-addon {
            //CSS for .input-group-addon when input is hovered
        }
    }
}

As @Martin suggested.

Richard Shi
  • 625
  • 1
  • 9
  • 21
  • 1
    +1 for the [**sibling combinator**](http://www.w3.org/TR/css3-selectors/#sibling-combinators). You could also just use the `+` (adjacent sibling combinator) if you only want the sibling immediately after. See more here (works already in SCC2): [http://www.w3.org/TR/CSS21/selector.html#adjacent-selectors](http://www.w3.org/TR/CSS21/selector.html#adjacent-selectors) – Martin Turjak Mar 03 '14 at 08:20
  • @Martin Thank you, I noted that in the answer. (Not sure what the etiquette is when someone adds info to my answer via comment, so do tell me if I should've done something else.) – Richard Shi Mar 03 '14 at 10:39
2

I think you are looking for something like this:

<style type="text/css">
.navbar {
  background: #000;
  &:hover .change{
    background: #ccc;
  }
}
</style>

<div class="navbar">
  <div class="change">
  </div>
</div>

If you hover above the navbar then the .change div will change colors. This is what I usually use instead of using jQuery for certain effect triggers.

RaySinlao
  • 156
  • 9
  • Yes, this works great if change is the child of navbar. I am looking to hover over change1 and have something done to change2 which are both children of navbar – Mohamed El Mahallawy Mar 03 '14 at 05:38