I have a header with titles and a shopping cart. I want different hover effect on the titles and the cart.
#menu-links {
position: relative;
color: white;
font-size: 17px;
}
#menu-links#title:after {
color: white;
display: flex;
content: '';
border-bottom: solid 3px violet;
transform: scaleX(0);
transition: transform 250ms ease-in-out;
transform-origin: 100% 50%
}
#menu-links#title:hover:after {
transform: scaleX(1);
transform-origin: 0 50%;
}
#menu-links#cart:hover {
color: violet;
}
<ul class="nav-menu">
<li class="nav-item"><a href="#" class="nav-link-main" id="menu-links title">Начало</a></li>
<li class="nav-item"><a href="#" class="nav-link-main" id="menu-links title">Lórèal Professionel</a></li>
<li class="nav-item"><a href="#" class="nav-link-main" id="menu-links title">Стайлинг</a></li>
<li class="nav-item"><a href="#" class="nav-link-main" id="menu-links title">Steam Pod</a></li>
<li class="nav-item"><a href="#" class="nav-link-main" id="menu-links cart"><svg
xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
class="bi bi-cart" viewBox="0 0 16 16">
<path
d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
</svg></a></li>
</ul>
I tried to set 2 id’s, but it did not work it broke more. Can someone help <3
3
Answers
Use CSS Variable and use it on hover. Use JavaScript and fetch that CSS variable and use addEventListener to listen on onmousehover event and when you hover on item then change the css variable color every time.
The
id
value cannot be used more than once and it cannot contain whitespace.As already commented, you should use CSS classes instead of id.
In fact, you can assign duplicate IDs or even multiple values to the id attribute.
But you shouldn’t do this, because it undermines the concept and benefits of IDs.
Currently, you’re using IDs just like classes – better use classes
Common usage for IDs
Hacky approach using attribute selectors
However, you could style elements as described in your example using attribute selectors
In fact, we’re "degrading" the otherwise highly specific ID (if we were selecting via
#menu-links
) to an arbitrary attribute selector like[id*="menu-links"]
.Better use classes for you nav an stick to commonly used best-practices.
Further reading