How does CSS "know" that the background of a PNG image is transparent?

Consider this PNG image of a Black circle with transparent background:


Untitled


Giving it CSS like background: orange; will change its background to Orange, even inside the circle.

It’s as if CSS can change the “machine code” of some images themselves, to say somwhat metaphorically.

How does CSS “know” that the background of a PNG image is transparent?
And by the way, was it always like that in the history of CSS?

1 Like

PNG image data foramat contain 4 bytes per pixel. 3 bites for the color and one byte for the alpha channel or opacity. So if the alpha channel of a pixel is 0, this pixel is transparent. If it is 128 it is half transparent and if it is 255 it is complete. So not even CSS but all software using a PNG image is able to work with this alpha channel and can do things like you explained

3 Likes

Nothing “changes”, the transparency is already coded into the image in its Alpha channel.
Instead of just three (RGB) channels like a Jpeg, PNG can have four, RGBA. That is Red, Green, Blue and Alpha (Transparency).
CSS doesn’t “know”, but the browser will display any image with Alpha with its transparent pixels invisible. So whatever is behind it may be seen.

3 Likes

As mentioned above css does no such thing. If something is transparent then you can see whatever is behind it.

You can set the background of an image container to whatever color you like or indeed another background image if required just like most other elements. You will only see the background though if the image has transparent sections.

Imagine two divs on top of each other with one green and one red. You can only see the one underneath if the top background is transparent or has transparent parts.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.