user1770961
user1770961

Reputation: 101

Background image won't show when hover in css

Got this code to work with:

<style type="text/css">
        body {
            margin: 0px;
        }

        #hallo {
            width: 960px;
            height: 600px;
            position: relative;
            margin: auto;
            border: solid 1px yellow;
        }
        #bg {
            width: 960px;
            height: 600px;
            position: absolute;
            background-image:url(torres.jpg);
            background-size: 960px 600px;
        }

        #t1 {
            width: 100px;
            height: 100px;
            position: absolute; 
            background-size: 100px 100px;
            border: solid 1px white;
        }

        #t1  {
            top: 100px;
            left: 600px;
            background-image:url(torres1.jpg);
        }

        #t1:hover ~ #bg {
            position: absolute;
            background-image:url(torres1.jpg);
            background-size: 960px 600px;
        }


    </style>

<section id="hallo">

    <div id="bg"></div>
    <div id="t1"></div>

</section>  

But I got a problem. When I take the mouseover the t1 div nothing happens. The background-image won't change to "torres1.jpg". Is there any solutions?

I'm noe able to use java for this.

Upvotes: 0

Views: 656

Answers (2)

Koen.
Koen.

Reputation: 27009

Swap #bg and #t1 and your sibling selector should work:

<section id="hallo">
    <div id="t1"></div>
    <div id="bg"></div>
</section>  

Upvotes: 0

David Thomas
David Thomas

Reputation: 253486

You haven't defined a :hover state for the #t1 element:

#t1  { /* non-hovered */
    top: 100px;
    left: 600px;
}

#t1:hover { /* hovered-over */
    background-image:url(torres1.jpg);
}

Edited in response to comment from OP:

Ah, you don't understand my question. What I am looking for is that the background-image in #bg to change when hover over the #t1 div.

This can't happen (yet), CSS can only affect elements that appear in the DOM later than the current element on whose interaction you're trying to style it.

Therefore while you could style #t1 based on the #bg:hover, but you cannot style a parent, or previous-sibling, based on the :hover of a child or later-sibling.

Upvotes: 2

Related Questions