How does converting an image to css work?

Question:

On the web there are examples of very complicated images made exclusively with css, such as the Mona Lisa in CSS .

Obviously, they must have used some algorithm to generate them.

I would like to know how they achieve it and if it is possible that the generated css is totally portable between the most common browsers.

Answer:

In this specific case, box-shadow is used to draw each pixel as a small colored shadow and positioned appropriately to form the resulting image.

This hack takes advantage of the following:

  • Multiple shadows can be defined for a single element
  • Each shade can be individually colored with any color
  • Each shadow can be positioned individually with respect to the original element.

Regarding the algorithm to generate it, it would be enough to go through the image pixel by pixel and convert each one of them to a new box-shadow , modifying color and position. To check it, it would be enough to read the code that appears linked in the example of your question, with which it has supposedly been generated: https://github.com/jaysalvat/image2css


It should be noted that, beyond the artistic value and the initial surprise that something like this can be done, this technique has no real value, since each pixel of the image is encoded with a minimum of 24 bytes, an order of magnitude greater than any efficient image encoding (JPEG, BMP, WebP, etc.)

Scroll to Top