Reputation:
I am trying to achieve this: on hover of my a element in my nav change the background color of a .background, my code is like so:
<li><a data-scroll href="#contact">Contact</a></li>
</ul>
<div class="background"></div>
</nav>
However the color only changes when I tell the css to change the color on hover of the ul
and if I tell to change it when I hover over an a
with class .header-about
it just won't do anything no matter what I try. I tried to be as clear as possible in explaining this.
Here is my whole mark-up:
.header-nav .background {
background: purple;
position: absolute;
width: 450px;
height: 550px;
top: 0;
transition: all 0.3s;
}
.header-nav ul .header-about:hover {
color: black;
}
.header-nav ul .header-about:hover + .background {
background: #2F94CC;
}
<nav class="header-nav text-left">
<ul>
<li><a data-scroll href="#about" class="header-about">About</a></li>
<li><a data-scroll href="#work">My work</a></li>
<li><a data-scroll href="#resume">Resumé</a></li>
<li><a data-scroll href="#contact">Contact</a></li>
</ul>
<div class="background"></div>
</nav>
I tried to be as clear as possible in explaining the problem.
Upvotes: 0
Views: 347
Reputation: 39322
You cannot select .background
with CSS on hover of .header-about
. However you can achieve this as follows:
$(function() {
$('.header-nav ul a').hover(function() {
$('.background').css('background', $(this).attr('data-color'));
}, function() {
$('.background').css('background', '');
});
});
.header-nav .background {
transition: all 0.3s;
background: purple;
position: absolute;
width: 450px;
height: 550px;
z-index: -1;
top: 0;
}
.header-nav ul li:hover {
color: black;
}
.header-nav .background {
background: #2F94CC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav class="header-nav text-left">
<ul>
<li><a data-scroll href="#about" data-color="#f00">About</a></li>
<li><a data-scroll href="#work" data-color="#0f0">My work</a></li>
<li><a data-scroll href="#resume" data-color="#05f">Resumé</a></li>
<li><a data-scroll href="#contact" data-color="#f00">Contact</a></li>
</ul>
<div class="background"></div>
</nav>
Upvotes: 1
Reputation: 2584
Your next sibling selector which is '+' will only work if the background div is positioned like this:
<nav class="header-nav text-left">
<ul>
<li>
<a data-scroll href="#about" class="header-about">About</a>
<div class="background"></div>
</li>
<li><a data-scroll href="#work">My work</a></li>
<li><a data-scroll href="#resume">Resumé</a></li>
<li><a data-scroll href="#contact">Contact</a></li>
</ul>
</nav>
Because it has to be after your selector element at the same level in the dom tree and next to your selected element.
You might have to go for a javascript solution if the positioning in your html cannot be changed.
Upvotes: 0