I have a navbar at the top of my page and I would like a rollover effect to occur where when you hover on a link, a light bulb icon appears directly above the link. What is the best way to achieve this with CSS?
.navbar .nav a, .navbar .nav .a {
font-size: 16px;
}
.navbar .nav a:hover, .navbar .nav .a:hover {
background-image: url('lightbulb.png');
background-repeat: no-repeat;
background-position: center top;
background-size: contain;
display:block;
}
CodePudding user response:
To be sure of getting the light bulb exactly above the text I think I'd put your background code into a pseudo element so that it can be positioned on top of the text.
This simple snippet leaves some space above the element using padding - it all depends on how you want to do this in the real example of course with the positioning of navbar perhaps?
a {
font-size: 16px;
padding-top: 20px;
display: inline-block;
position: relative;
}
a::before {
content: '';
position: relative;
height: 20px;
aspect-ratio: 1 / 1;
left: 50%;
top: 0;
transform: translate(-50%, -100%);
display: inline-block;
}
a:hover::before {
background-image: url('https://i.stack.imgur.com/dp2LF.png');
background-repeat: no-repeat;
background-position: center top;
background-size: contain;
}
<a href='#'>Hover</a>
CodePudding user response:
body {
margin: 3rem;
}
nav {
display: flex;
gap: 2.5rem;
}
nav div {
cursor: pointer;
}
nav li {
position: relative;
list-style: none;
}
nav li::before {
content: '';
position: absolute;
width: 30px;
height: 30px;
left: calc(50% - 15px);
top: -30px;
display: none;
background-image: url('https://media.istockphoto.com/vectors/light-bulb-icon-vector-light-bulb-ideas-symbol-illustration-vector-id1167459261?k=20&m=1167459261&s=170667a&w=0&h=3KSKkFUNQoPvoS70bzIWeT1fXRuB9rzap6VC1HipCgg=');
background-size: contain;
}
nav div:hover li::before {
display: block;
}
<nav>
<div>
<li>List Item</li>
</div>
<div>
<li>List Item</li>
</div>
</nav>