How to select parents sibling with CSS?

5.1k views Asked by At

When I hover on the first <li>, I want to change the background-color of the .arrow-tip class. Can you help me find the correct CSS rule?

HTML:

<nav>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
    </ul>
</nav>
<div class="arrow-tip">A triangle tip for the nav menu</div>

CSS:

nav > ul > li:nth-child(1):hover ~ .arrow-tip {
    background-color: #FF0;
}

I want a PURE CSS Solution for this.

1

There are 1 answers

0
Stickers On BEST ANSWER

No, it's not possible with CSS currently, read this.

However, I guess you could do something like this JsFiddle instead.

ul {
    list-style: none;
    padding: 0;
    width: 45px;
    text-align: center;
    position: relative;
}
li {
    background: silver;
    margin: 0 0 5px;
}
li:after {
    content:"\25be";
    font-size: 2em;
    position: absolute;
    left: 10px;
    top: 35px;
}
li:hover:after {
    z-index: 1;
}
li:nth-child(1):hover:after {
    color: red;
}
li:nth-child(2):hover:after {
    color: blue;
}
<ul>
    <li>A</li>
    <li>B</li>
</ul>

Edit: Here is the JsFiddle for what OP really wants to achieve.

Please follow the comments above if you're interested.

.menu {
    list-style: none;
    padding: 0;
}
.menu > li {
    position: relative;
    background: fuchsia;
    width: 100px;
    height: 20px;
    display: inline-block;
    vertical-align: top;
}
.submenu {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    list-style: none;
    padding: 30px 0 0;
    margin: 0;
}
.submenu > li {
    background: fuchsia;
    display: block;
}
.submenu > li:before {
    content: "";
    position: absolute;
    top: 20px;
    left: 50%;
    margin-left: -10px;
    width: 0;
    height: 0;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-bottom: 10px solid aqua;
    z-index: -1;
}
/* hide */
.submenu {
    display: none;
}
/* hover */
.menu > li:hover {
    background: aqua;
}
.menu > li:hover > ul {
    display: block;
}
.submenu > li:hover {
    background: aqua;
}
.submenu li:not(:nth-child(1)):hover:before {
    border-bottom: 10px solid fuchsia;
    z-index: 0;
}
<ul class="menu">
    <li>one
        <ul class="submenu">
            <li>a</li>
            <li>b</li>
            <li>x</li>
            <li>y</li>
            <li>z</li>
        </ul>
    </li>
    <li>two
        <ul class="submenu">
            <li>c</li>
            <li>d</li>
        </ul>
    </li>
    <li>three
        <ul class="submenu">
            <li>e</li>
            <li>f</li>
        </ul>
    </li>
    <li>four
        <ul class="submenu">
            <li>g</li>
            <li>h</li>
        </ul>
    </li>
</ul>