0

how to change properties of a parent div on hover of child div. can it be done with pure css ?

html:

<div class="parent">
    <div class="child">
    </div>
</div>

css:

.parent{width:200px;height:100px;background:#cccccc;}
.child{width:200px;height:100px;background:transparent;}
MarcinJuraszek
  • 118,129
  • 14
  • 170
  • 241
  • 1
    You will need to use Javascript or Jquery. – Lowkase Feb 28 '13 at 15:15
  • You can probably apply the `:hover` pseudo-selector to both the parent and div and have it change (a child is going to bubble up to parent, but only apply it when both are hovered). Though this only can change the child, not that parent. – Brad Christie Feb 28 '13 at 15:15
  • what properties do you need to change ? – Nick Andriopoulos Feb 28 '13 at 15:15
  • There is no way to do this using pure css (see http://stackoverflow.com/questions/45004/complex-css-selector-for-parent-of-active-child). You'll have to use javascript. – Joshua Dwire Feb 28 '13 at 15:17

3 Answers3

1

Not with plain CSS you need some form of script to notify the parent that the child is being hovered(eg.):

<div id="parentId" class="parent">
    <div id="childId" onmouseover="doOnMouseOver()" onmouseout="doOnMouseOut()" class="child">
    </div>
</div>
<script type="text/javascript">
    function doOnMouseOver() {
        var parentNode = this.parentNode;
        var newParentClass = parentNode.getAttribute('class') + 'child-beeing-hovered';
        parentNode.setAttribute('class', parentClass);
    }

    function doOnMouseOut() {
        var parentNode = this.parentNode;
        var newParentClass = parentNode.getAttribute('class').replace('child-beeing-hovered', '');
        parentNode.setAttribute('class', parentClass);
    }
</script>

Note that I've added ids to your html elements so that I can get a hold of them with javascript without making the code unnecessary complex nor using a third party library like jQuery.

Note that you need also to bind onmouseout or otherwise the parent element will keep the new class child-beeing-hovered.

jQuery actually makes your job easier but you should try doing this with javascript at least once.

I hope it helps.

teratzul
  • 41
  • 5
0

There is no parent selector in CSS.

You can find quite good explanation why it's not supported here: http://snook.ca/archives/html_and_css/css-parent-selectors

MarcinJuraszek
  • 118,129
  • 14
  • 170
  • 241
0

Is there a reason you do not want to use JavaScript or JQuery?

You could simply:

$("#child_id").hover(function (){
  $(this).parent("div").addClass("some-class")
});
jdbosley
  • 166
  • 1
  • 2
  • 8