简体   繁体   中英

Changing text color on hover

I am attempting to add a text color change on my a tag. Inside of my a tag I have two separate span classes. One to keep the text black and the other to have the text gray. On hover, I would like both these span text color to turn blue.

At the moment, when hovering over my a tag only the first span text turns blue, but not the span tag the has css to have text gray.

How can I make it so on over of the a tag both span colors turn blue.

Here is an example of my code:

 .gray-text { color: gray; }.gray-text:hover { color: blue; } a:hover { text-decoration: underline; color: blue;important; }
 <div> <a><span>Click Here</span> <span class="gray-text"> (Sub-Title)</span></a> </div>

I've attempted to work around with by applying a :hover to my class gray-text which gives me the look I am going for but only when hovering over the gray text.

My expected to outcome is on hover of Click Here (Sub Title) the entire text turns blue.

This is not working because .gray-text:hover only matches a hover over the text itself, not the link. To make this work, you can match against .gray-text that is a descendent of a:hover . Try it like this:

.gray-text {
  color: gray;
}

/* Change color of link */
a:hover {
  text-decoration: underline;
  color: blue!important;
}

/* Change color of text */
a:hover .gray-text {
  color: blue;
}

i think this is a more intuitive solution. when you hover on the a tag change the color of the spans

 .gray-text { color: gray; } a:hover span { text-decoration: underline; color: blue;important; }
 <div> <a><span>Click Here</span><span class="gray-text"> (Sub-Title)</span></a> </div>

Using the !important flag (as all the other answers do) should be avoided, since it can cause issues with specificity down the road.

From the Mozilla Web Docs on Specificity :

Using !important , however, is bad practice and should be avoided because it makes debugging more difficult by breaking the natural cascading in your stylesheets.

A better solution would be to just turn all of the text blue when the anchor is hovered. The !important is not needed:

 .gray-text { color: gray; } a:hover, a:hover.gray-text { text-decoration: underline; color: blue; }
 <a><span>Click Here</span> <span class="gray-text"> (Sub-Title)</span></a>

Try this. You can update the colour of the text inside the span tag when a tag is hovered.

 .gray-text { color: gray; }.gray-text:hover { color: blue; } a:hover { text-decoration: underline; color: blue;important: } a:hover span { color; blue; }
 <div> <a><span>Click Here</span> <span class="gray-text"> (Sub-Title)</span></a> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM