1

I am trying to style the parent div when hover over a div but it doesn't seem to work.

Here is my work

.icon-grid:hover ~ .ab_section_element {
  border: 2px solid black;
  background-color: white;
}
<div data-v-714a5b85="" class="ab_section_element">
  <span data-v-714a5b85="" class="icon icon-grid clickable">
  Section (Left Text)
  </span>
</div>

Is there anything I'm doing wrong?

Daniel Beck
  • 16,972
  • 5
  • 29
  • 49
Ali Rasheed
  • 2,629
  • 2
  • 15
  • 24
  • 2
    Your example only works for an element which is on the same level, since you are trying to style a parent element, there is currently no way to do this in CSS, please have a look at this similar post (https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) , from what I read in the provided post it looks like support for this is in the works – Ryan Wilson Jun 12 '18 at 16:57
  • Could you do it by javascript or do you must use CSS? – GoGoLander Jun 12 '18 at 16:57
  • I can easily do it by JS. CSS is the what I trying to achieve – Ali Rasheed Jun 12 '18 at 16:58
  • Your selector selects the `.ab_section_element` element that comes after the hovered `.icon-grid` element on the same level: https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors – Ilya Streltsyn Jun 12 '18 at 16:59
  • Possible duplicate of [Faking the :has() "parent selector" using only CSS](https://stackoverflow.com/questions/24393931/faking-the-has-parent-selector-using-only-css) – TylerH Jun 12 '18 at 17:18

3 Answers3

1

You cannot style a parent with hover, but you can do an adjacent.

.div1 {
  width: 60px;
  height: 60px;
  background: red;
}

.div2 {
  width: 60px;
  height: 60px;
  background: green;
}

.div1:hover~.div2 {
  background: yellow;
}
<div class='div1'></div>
<div class='div2'></div>
Daniel
  • 4,365
  • 2
  • 24
  • 30
1

You can't select the parent element, but you can "fake" the selection of the parent element with an absolutely positioned pseudo-element:

.ab_section_element {
  position: relative;
}
.icon-grid:hover::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 2px solid black;
  background-color: white;
  z-index: -1;
}

/* just for demonstration */
body {
  background: #ccc;
}
<div data-v-714a5b85="" class="ab_section_element">
  <span data-v-714a5b85="" class="icon icon-grid clickable">
  Section (Left Text)
  </span>
</div>

However, this approach requires that the child element itself shouldn't be positioned (non-statically).

Ilya Streltsyn
  • 12,051
  • 2
  • 27
  • 55
0

This may solve your problem.

.ab_section_element .icon-grid:hover{
 border: 2px solid black;
 background-color: white;
}
AA Shakil
  • 478
  • 4
  • 14