1

Is this possible with css only? I have the following:

 <div class="container">
      <img src=#>
 </div>

How do I get .container to have a box-shadow (and other styling) when and only when img is in the state :hover?

shenku
  • 9,802
  • 10
  • 57
  • 109
bsapaka
  • 3,752
  • 8
  • 30
  • 60

3 Answers3

1

As people have stated there is no CSS parent selector, for a number of good reasons as stated in the linked duplicate question.

However, with the code you've shown, you can just apply the hover pseudo-selector to your parent element and it will achieve almost the exact same functionality.

So this:

div:hover{
    border:1px solid red
}

Would work only because you have a single child, and would have the issue that if you hover adjacent to the img but not directly on it the parent will still have styles applied because its a block element.

You can convert it to inline-block to limit this, like so:

div{
    display:inline-block;
}
div:hover{
    border:1px solid red;
}

However, this will have implications for how other sibling elements to the parent flow.

0

You can use jQuery:

$("span").hover(
  function () {
    $(this).parent().addClass("add-class");
  },
  function () {
    $(this).parent().removeClass("add-class");
  }
);

Here is the demo http://jsfiddle.net/Sv6Av/

You can replace span with another tag such as img

Nizamil Putra
  • 572
  • 1
  • 7
  • 26
-1

Nope. No parent selector in css yet. You will have to resort to js for now. For more explanation read this

Lokesh Suthar
  • 3,153
  • 1
  • 13
  • 28