Slight difference in HTML elements’ semi-transparency

There’s a slight difference in making HTML elements semi-transparent using:

  • opacity attribute and
  • alpha channel

I was not aware of that difference, therefore I posted this short article to keep that fact in my memory.

Suppose you have a piece of HTML code like that:

<div class="compact">
    <img src="<?php echo $img; ?/>" alt="< ?php echo $title; ?>" />

    <div class="overlay">
        <h2><a href="<?php echo $url; ?>">< ?php echo $title; ?></a></h2>

        <a href="<?php echo $url; ?>">read mode »</a>
    </div>
</div>

And that the image below an overlay covers entire area and overlay spans over it.

Now, if you set overlay semi-transparency using opacity attribute, like that:

.layout-compact .overlay {
    background: #183882;
    opacity: 0.8;
}

then you set it to overlay and all elements, it includes. I.e. if title and read more link are white, they’ll become a little bit grey, due to opacity.

If you, on contrary, use alpha-channel instead:

.layout-compact .overlay {
    background: rgba(24, 56, 130, 0.8);
}

then you set semi-transparency only to overlay itself. I.e. white color of title and line remain unchanged.

This maybe obvious to others, but wasn’t that obvious to me, so I wrote this down for future reference.

Leave a Reply