Link1

Change 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 selector in CSS, when I move the mouse cursor on Link1 or Link2, changes background-color

of container

. Since I am a beginner and think I have some problems.

+3


source to share


3 answers


CSS4 (yup) introduces the :has()

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

If supported, then the syntax (currently suggested) is:



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 will need to rely on Javascript like jQuery like has

( http://api.jquery.com/has/ ).

+2


source


The short answer is no . Cannot select parents or in ascending order.

The best you can do is change the HTML and use a different element to fake the parent's background.

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 out this demo http://jsfiddle.net/g7brnb9q/

About the selector ~

helps to select elements for sibling, in this case any element with a class fake

after links.

Chek Here's more about it GO HERE

+1


source


No parent selector in css ...

If the javascript approach suits you, you can 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";
};

      

0


source







All Articles