Asif Ali
Asif Ali

Reputation: 281

How to change css of one class when hovering over another?

I am new to css especially combinators but I am trying to change css of a p element when hovering over a h1 element both of which are in a div of class "a" but I can't figure out how to do it.Here is my code

HTML

<div class="a">
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</div>

CSS

div.a h1:hover ~ div.a p {color:red;}

So what am I doing wrong?

Upvotes: 2

Views: 511

Answers (3)

NewToJS
NewToJS

Reputation: 2772

You don't need to target the div element again.

All Paragraphs JsFiddle Demo

First Paragraph Jsfiddle Demo

div.a h1:hover~p{color:red;}
<div class="a">
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>
<p>Some other text.</p>

If you only want to target the first <p> paragraph tag then you can use

div.a h1:hover+p{color:red;}
<div class="a">
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>

If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.

I hope this help. Happy coding!

Upvotes: 3

Joshua Rose
Joshua Rose

Reputation: 390

If you are using jQuery you may use the following code to transform the paragraph.

$('div.a h1').hover(function() {
        $(this).siblings('p').css(color: red;);
    }, function() {
        $(this).siblings('p').css( << Previous Css >> );
    }
});

Upvotes: 1

Olivier Boiss&#233;
Olivier Boiss&#233;

Reputation: 18113

This solution should work :

div.a > h1:hover + p {
    color:red;
}

> h1:hover to select h1:hover element where the parent is div with class 'a'

+ p to select p element that are placed immediately after h1:hover element

Upvotes: 2

Related Questions