Search code examples
csscolorscss-transitionsopacity

CSS Transition: Opacity vs changing Background-Color?


I am curious if there is an industry standard for transitioning colour since there are multiple ways to accomplish the desired transition effect.

There are multiple ways to make a particular colour brighter or darker to indicate to the user that the element is intractable.

For example, if you have a p tag and you want to add a hover over effect you could:

HTML

<div><p> P tag text </p></div>

CSS v1 using opacity

div {
background-color:black;
}

p {
color: white;
opacity: 0.8;
transition: opacity 0.2s ease-in-out;
}

p:hover {
opacity: 1;
}

CSS v2 using colour

div {
background-color:black;
}

p {
color: #ccc;
transition: color 0.2s ease-in-out;
}

p:hover {
color: #fff;
}

As far I'm aware both methods provide similar results however, I am still curious whether or not there is a correct way to do this kind of thing.


Solution

  • The main thing you should realize is that opacity affects an entire element and all its descendants, whereas color and background-color do not.

    In your simple example, white text with reduced opacity on a solid black background looks gray, so the visual effect is basically the same as changing the color from gray to pure white.

    But in any more complicated example – say, the background of your paragraph's parent div is an image rather than a solid color, or you're using opacity on an element that contains other elements and not merely on text – what you're gonna end up with is things that truly look see-through. That also may mean that text becomes harder to read.

    So the answer is less about there being any particular industry standard and more about choosing the right tool for the job. If you just want to make some text a lighter color, transition color itself. If you want to make things see-through, use opacity.

    That's the theory, anyway, but in real life sometimes it's not that clean cut. Maybe a designer gives you a mockup with text that's color: #C44242; opacity: 0.87 on top of a solid-colored background that's background-color: #B48927. You could compute what the opaque version of that text color would be, but it may not be worth your time to do so. The world won't end if you just stick with opacity.