LeCdr
LeCdr

Reputation: 323

Changing background-color of parent element on hover

Below is my html code.

        <div class="container">
            <a class="link1" href="">Link1</a>
            <a class="link2" href="">Link2</a>
            <a class="link3" href="">Link3</a>              
        </div>

Is there any selectors in CSS that when I hover mouse on Link1 or Link2, the background-color of container gets change. Since I am new & self thought that's why I have some problems.

Upvotes: 3

Views: 5509

Answers (3)

DaniP
DaniP

Reputation: 38252

The Short Answer is No. There is no way to select parents or in ascending order.

The best you can do is change the HTML and use another element to fake the background of the parent.

Like this:

HTML

 <div class="container">
        <a class="link1" href="">Link1</a>
        <a class="link2" href="">Link2</a>
        <a class="link3" href="">Link3</a> 
        <div class="fake"></div>
 </div>

CSS

.fake {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:yellow;
}
.link1, .link2, .link3 {
    position:relative;
    z-index:1;
}
.link1:hover ~ .fake {
    background:#CCC;
}
.link2:hover ~ .fake {
    background:brown;
}
.link3:hover ~ .fake {
    background:orange;
}

Check This Demo http://jsfiddle.net/g7brnb9q/

About the ~ selector helps to select sibling elements, in this case any element with fake class after the links.

Chek Here more about this GO HERE

Upvotes: 1

LcSalazar
LcSalazar

Reputation: 16841

There is no parent selector on css...

If it's ok for you to have a javascript approach, you could do something like:

document.getElementsByClassName("link1")[0].onmouseover = function() {
    this.parentNode.backgroundColor = "red";
};
document.getElementsByClassName("link2")[0].onmouseover = function() {
    this.parentNode.backgroundColor = "green";
};
document.getElementsByClassName("link3")[0].onmouseover = function() {
    this.parentNode.backgroundColor = "blue";
};

Upvotes: 0

Dai
Dai

Reputation: 155250

CSS4 (yup) introduces the :has() psuedo-class ( http://dev.w3.org/csswg/selectors4/#relational ) however this not currently supported by any current (as of September 2014) engine or browser.

If it was supported, then the (currently proposed) syntax would be:

div.container:has(a.link1:hover) { background-image("link1.png"); }
div.container:has(a.link2:hover) { background-image("link2.png"); }
div.container:has(a.link3:hover) { background-image("link3.png"); }

Until then, you'll need to rely on Javascript, such as jQuery's similar has ( http://api.jquery.com/has/ ).

Upvotes: 2

Related Questions