Issue
I'm trying to create re-usable styling for in-page navigation. There is a default style, assigned by ID to the enclosing <nav> element. I also need to have an alternate style for certain special <a> elements within that <nav> element.
I assigned a class to one <a> element and then attempted to style it to mixed success. Some properties changed, but others only if I force an override with "!important".
While I can get by with this, it feels like a hack. What am I'm missing to properly target these specific links?
#page-nav a {
border: 2px solid black;
border-radius: .3rem;
padding: .25rem .5rem;
line-height: 2.25;
text-decoration: none;
font-weight: 700;
color: black;
}
#page-nav a:hover {
background-color: black;
color: white;
}
a.pageNavAlt:link {
background-color: black; /* WORKS */
/* color: red; DOESN'T WORK */
color: red !important; /* WORKS */
}
a.pageNavAlt:hover {
/* background-color: darkred;
color: yellow; DOESN'T WORK */
background-color: darkred !important; /* WORKS */
color: yellow !important; /* WORKS */
}
<nav id="page-nav">
<a class="pageNavAlt" href="#">Alternate link</a> <a href="#">Standard link 1</a> <a href="#">Standard link 2</a>
</nav>
Solution
Because #page-nav a
(and #page-nav a:hover
) have higher precedence in the CSS rules due to the use of an id
. So the styles in a.pageNavAlt:hover
are being applied, but are being over-ruled by the styles in #page-nav a:hover
.
You can add the id
selector to the additional styles:
#page-nav a {
border: 2px solid black;
border-radius: .3rem;
padding: .25rem .5rem;
line-height: 2.25;
text-decoration: none;
font-weight: 700;
color: black;
}
#page-nav a:hover {
background-color: black;
color: white;
}
#page-nav a.pageNavAlt:link { /* <-- here */
background-color: black;
color: red;
}
#page-nav a.pageNavAlt:hover { /* <-- and here */
background-color: darkred;
color: yellow;
}
<nav id="page-nav">
<a class="pageNavAlt" href="#">Alternate link</a> <a href="#">Standard link 1</a> <a href="#">Standard link 2</a>
</nav>
Answered By - David
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.