The :hover
effect isn’t working, and I’m not sure why.
I’m fairly new to CSS, and as I was experimenting with some exercises on my own, I came across an issue. When I hover over the #hey
element, its color is supposed to change, but it’s not working. I’m wondering what might be causing this problem and how I can resolve it. To help you understand better, I’ve also included a video demonstration and the code I’ve written.
Here is a GIF link for you to see it better.
body {
font-family: "Open Sans", sans-serif;
height: 3000px;
margin: 0;
}
h1 {
text-align: center;
}
#container {
background-color: #003049;
width: 90%;
height: 500px;
margin: 0 auto;
border: 5px solid #003049;
position: relative;
}
.header {
position: fixed;
display: flex;
width: 90%;
height: 500px;
}
.header div {
width: 100%;
height: 100%;
transition: all 0.2s;
}
.header div:nth-of-type(1):hover {
background-color: transparent !important;
}
.header div:nth-of-type(2):hover {
background-color: transparent !important;
}
.header div:nth-of-type(3):hover {
background-color: transparent !important;
}
.header div:nth-of-type(4):hover {
background-color: transparent !important;
}
.header div:nth-of-type(5):hover {
background-color: transparent !important;
}
#hey {
color: white;
font-family: "Open Sans", sans-serif;
font-size: 3em;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#hey:hover {
color: red;
}
<h1>Trying something page</h1>
<section id="container">
<div id="hey">HEY</div>
<div class="header">
<div style="background-color: #80ffdb"></div>
<div style="background-color: #64dfdf"></div>
<div style="background-color: #48bfe3"></div>
<div style="background-color: #5390d9"></div>
<div style="background-color: #6930c3"></div>
</div>
</section>
2
Answers
The hover function for the
#hey
element isn’t working because there’s already an active hover on the surroundingdiv
.Put another way, there’s no access to the
#hey
element until you hover over the surroundingdiv
. At that point, you’re trying to trigger an additional hover, which the browser just ignores.If you remove the
div
hover, you’ll see the#hey
hover works.If you have the option, restructure the HTML. Try nesting the
#hey
element inside thediv
.Your issue is that you have an element sitting on top of your "Hey". Even though your third rectangle has a transparent background, it’s still there in the eyes of the browser. This means that when it looks to you like you’re hovering over "Hey," you’re actually hovering over your transparent background and the browser isn’t getting the signal that "Hey" is being hovered on.
Depending on what your ultimate goal is, one solution is to move they "Hey" to the third rectangle.
HTML that replaces your third
div
.CSS that replaces all your styles for
#hey
.You can see the whole thing together in this CodePen.