1

I'm currently working some code for my website and I came to this problem. I want to change background of paragraph on div's hover but it doesn't seems to works. I found some tutorials and I don't know what is wrong with my code

<style>

    .more_news{
        padding:10px;
        border:1px double lightgray;
        width:170px;
        height:100px;
        overflow: hidden;
        margin:0px; 
    }

    .more_news img{
        width:100%;
        height:100%;
    }

    .more_news p{
        color:green;
        position:absolute;
        display:block;
        background:gray;
        margin-top:-40px;
        width:170px;
        height:40px;
    }

    .more_news div:hover ~ .more_news p{
        background:red;
    }

</style>

<div class="more_news">
    <img src="images/proba1.png" class="more_news_img">
    <p class="more_news_p">Hello</p>
</div>
0

2 Answers 2

3

All you need to do is select the class and element like so:

p.more_news_p:hover {
    background:red;
}

No need for ~ or any other combinator/selector

http://jsfiddle.net/7H4XW/

Or, if you want to change the background when you hover over the entire div you can do something like this:

.more_news:hover p.more_news_p {
    background:red;
}

http://jsfiddle.net/qfb9Z/

Sign up to request clarification or add additional context in comments.

Comments

1

"I want to change background of paragraph on div's hover but it doesn't seems to works."

You'd just use:

.more_news:hover > .more_news_p {
  background:red;
}

You were using the general sibling selector ~, which selects sibling elements after that element.

whereas you actually want to target the paragraph which is a child element - hence the use of the direct child selector (>)

jsFiddle here

3 Comments

@Roman How doesn't it? Your question says when you hover the div you want to highlight the paragraph?
Ah thank u, it is working now, but can u explain me when i use ~ ? :)
I go sleep now, will see that tomorrow. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.