1

I'm trying to set when p is hover it will affect the properties of img from another div inside a divs.

.class2 p:hover > .class3 {
    background: black;
}



<div class="class1">
    <div class="class2">
        <p>text</p>
    </div>
    <div class="class2">
        <div class="class3">
        </div>
    </div>
</div>
pavel
  • 26,538
  • 10
  • 45
  • 61
boris
  • 13
  • 4

3 Answers3

2

It isn't possible in general (in CSS you can target just siblings or children, not parents).

In this case you can use :hover on parent element (.class2).

.class2:hover + .class2 {
    background: black;
}
<div class="class1">
    <div class="class2">
        <p>text</p>
    </div>
    <div class="class2">
        <div class="class3">
        text in the second div
        </div>
    </div>
</div>
pavel
  • 26,538
  • 10
  • 45
  • 61
  • i needed only the text inside the p tag will have the hover and not all the class2 .. but thanks ill change my html .. – boris Nov 23 '20 at 16:59
  • @boris: Then it's not possible without changing HTML markup. If you need/want to help with HTML markup, just show us what you have, what you need, etc. I've worked with markup you showed us - and there was `p` the only one content of `.class2`... :-) – pavel Nov 23 '20 at 18:21
  • no its ok just wanted to know if there is a way.. i fix it by changing the html structure thanks guys – boris Nov 25 '20 at 15:37
0

I think you can use pointer-events in this case. I will edit your code a bit.

<style>
    .class2{background: #ddd}
    div.class2 {  
        pointer-events: none;
    }

    div.class2 p {
        pointer-events: auto;
    }

    div.class2:hover {
        background: yellow;
    } 
    div.class2:hover + .class2{
        background: yellow;
    } 
</style>
<div class="class1">
    <div class="class2">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <p>text</p>
    </div>
    <div class="class2">
        <div class="class3">
            text2
        </div>
    </div>
</div>
Bai Nguyen
  • 814
  • 7
  • 16
0

You can use a CSS post-processor library like Axe.

In this instance the CSS rule would use the \ selector, like this:

.class2 p:hover \ .class3 {
    background: black;
}

Working Example:

div {
  border: 1px solid rgb(255, 0, 0);
  box-sizing: border-box;
}

.class1 {
  width: 240px;
  height: 160px;
}

.class2 {
  width: 160px;
  height: 80px;
}

.class3 {
  width: 80px;
  height: 80px;
}

.class2 p:hover \ .class3 {
    background: black;
}
<div class="class1">
    <div class="class2">
        <p>text</p>
    </div>
    <div class="class2">
        <div class="class3">
        </div>
    </div>
</div>

<script src="https://rouninmedia.github.io/axe/axe.js"></script>
Rounin
  • 27,134
  • 9
  • 83
  • 108