Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

css - Is it possible to change only the alpha of a rgba background colour on hover?

I have a set of <a> tags with differing rgba background colours but the same alpha. Is it possible to write a single css style that will change only the opacity of the rgba attribute?

A quick example of the code:

 <a href="#"><img src="" /><div class="brown">Link 1</div></a>
 <a href="#"><img src="" /><div class="green">Link 2</div></a> 

And the styles

a {display: block; position: relative}
.brown {position: absolute; bottom: 0; background-color: rgba(118,76,41,.8);}
.green {position: absolute; bottom: 0; background-color: rgba(51,91,11,.8);}

What I would like to do is write a single style that would change the opacity when the <a> is hovered over, yet keep the colour unchanged.

Something like

a:hover .green, a:hover .brown {background-color: rgba(inherit,inherit,inherit,1);}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is now possible with custom properties:

.brown { --rgb: 118, 76, 41; }
.green { --rgb: 51, 91, 11; }

a { display: block; position: relative; }
div { position: absolute; bottom: 0; background-color: rgba(var(--rgb), 0.8); }
a:hover div { background-color: rgba(var(--rgb), 1); }

To understand how this works, see How do I apply opacity to a CSS color variable?

If custom properties are not an option, see the original answer below.


Unfortunately, no, you'll have to specify the red, green and blue values again for each individual class:

a { display: block; position: relative; }

.brown { position: absolute; bottom: 0; background-color: rgba(118, 76, 41, 0.8); }
a:hover .brown { background-color: rgba(118, 76, 41, 1); }

.green { position: absolute; bottom: 0; background-color: rgba(51, 91, 11, 0.8); }
a:hover .green { background-color: rgba(51, 91, 11, 1); }

You can only use the inherit keyword alone as a value for the property, and even then the use of inherit isn't appropriate here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...