A visitor wrote to say that she had read my guide on How to Embed an Image to Get a Self-Contained Web Page, which dealt with foreground images, that is, those you specifically place on a web page as part of the content, but wondered if there was also a way to store an entire background picture within a web page or CSS file.
Unlike normal images, which are typically placed in <img>
tags in the
HTML,
background images are usually inserted in the
CSS.
The CSS may be either in an external style sheet file, or within the web page itself.
There is indeed a way to store a background image within the CSS code itself. You will have to use what is known in the web standards as a data URL.
You will need to know some HTML and CSS (although you don't need to be an expert), otherwise you will find this article difficult or impossible to follow.
This article deals only with storing background images within the style sheet. It doesn't address how you insert a normal (foreground) picture into your web page. See my other article for more information on that.
If you have no specific need to embed the image, you should just use the standard way
of inserting background images. For example, the following code uses a picture called "mypicture.png" as the
background for a selector named #demo
:
Contrast the simple code above with the large number of steps (described later) that you need to take to embed the image.
Embedding an image into your CSS does not prevent people from copying it. They can still copy the data URL code and use it verbatim on their page. Or they can save it as a separate file and convert it back into a picture. This method was not designed as a means to protect your images over and above the usual copyright protection. It is just a different way of putting pictures onto a website, with its own advantages and disadvantages.
It's useful for HTML email messages, since you can embed pictures into the message so that they show up when your recipients view it. You will not need to depend on a web server somewhere to host the picture, since everything is self-contained. The message will also display properly even if your visitors have set their email program or web email service not to show images hosted externally.
If you are distributing a document in the HTML format to someone (eg on a USB drive, or together with your computer program as its documentation), it may be handy to have everything in a single file. That way, you will avoid problems with your recipients/users not copying the image files needed for the document to be displayed properly, and then complaining that your page is broken.
There are undoubtedly other possible reasons for embedding images in the HTML/CSS.
It adds extra steps that you need for each picture you embed. And if you make changes to your image, you will have to go through all the steps again. Contrast this with the normal method, where you can just modify the image file directly, and you are done.
The textual equivalent of your image takes up more space than the original one. That is because every byte in the original picture is now represented by the more limited character set of small and capital letters, numbers and the "/" and "+" characters.
An analogy may be helpful here: it's as though previously you had a vocabulary of (say) 30,000 words to describe a particular object. So you could use the most apt word to say what you needed to say (eg, "that is a green frog"). But if you are restricted to a rudimentary vocabulary of (say) 100 words, the same description will have to be very much longer, because you will need a whole paragraph to replace the precise terms you previously used (eg, the word "frog" is no longer in your vocabulary, so you even have to describe the animal in simpler terms).
Note that this is just an analogy. The real situation is actually not as dire as a reduction of English vocabulary, since the bytes used for an image have a limited range that can be more easily expressed with alternatives than genuine human language, which must encompass everything. But the basic notion that you're expressing something with a more limited "language", and therefore need to say more to accomplish the same result, stands.
It adds to the bandwidth used by your web pages. This is the result of your image taking up more space.
And if the picture is stored in a <style>
element within the web page itself, as opposed
to being in an external style sheet, web browsers cannot cache it to reduce the amount they have
to download each time. In such a case, if it appears on multiple pages, it will be re-downloaded with every
page, every time, since it is part of those pages itself.
This adds to your site's data traffic usage and the bandwidth used by your visitors (which may be a concern if they are using a mobile phone on a metered data plan).
Old browsers (eg, Internet Explorer 8 and earlier) do not support data URLs in the CSS.
In general, for maximum compatibility, you should only embed small pictures. There are no requirements in the standards specifying the size a web browser should support, so browsers vary in what they can handle. For example, Internet Explorer 8 to 11 limits the size of the embedded data to 32 KB, and Microsoft Edge to 4 GB.
But even if there are no file size constraints, this facility was not really meant to be used for large images.
Before you can embed the picture, you will have to get the text equivalent of the image. How this is done depends on the operating system you're using.
If you use Windows, open a command prompt. You can do this by clicking the Start menu, typing "command prompt", and clicking the "Command Prompt" suggestion that pops up at the top of the menu.
A window will open, and you will be deposited at a line that says something like "C:\Users\christopherheng>". Don't worry if it doesn't say exactly that; the name that appears after "Users" depends on your Windows account name.
Now navigate to the folder containing your image. For example, if you placed your picture or photo on your desktop, type the following command and hit the ENTER key when you are done.
To convert the file, we will use a built-in command line program called "certutil" that comes with Windows.
Let's say that your file is called "mypicture.png". Type the following line into the command prompt, followed by the ENTER key.
Certutil will proceed to create a file called "mypicture.txt
" containing the text equivalent of your image.
This text representation of your picture is in something known as the Base64 encoding, which is used for a wide variety
of things on the Internet, such as email.
There are numerous commands available on Unix-type systems to convert the image to its textual form, including "openssl", "uuencode", "perl", "base64" and probably more. I will only describe the procedure for using "base64".
If you use macOS, and your image is called "mypicture.png", the command line is:
On Linux and BSD systems, it is:
Mac users will need to run the Terminal application to be able to type that command. I'm sorry, but I don't have a Mac, so I can't tell you how to do that. Linux users should just open up a shell or terminal window (but if you are a Linux user, you probably don't need me to tell you that).
You will also need to change to the directory where the picture is saved, before invoking base64. The command
to do this is "cd [path]
", where "cd" means "change directory" and "[path]" stands for the full path,
that is, the directory name starting from the topmost "/" directory. For example, if your picture is saved as
"/home/chris/images/mypicture.png", type "cd /home/chris/images
" to go to that directory.
The base64 command line given earlier creates a text file called mypicture.txt
containing a
representation of your image in something known as Base64 encoding. The latter is widely used on the Internet
for a number of things, including email.
Whichever system you're using, at the end of this step, you will have a file called "mypicture.txt
".
Open your CSS file in a plain text editor. Windows users already have a plain text editor called Notepad on their system. Likewise, macOS users also have TextEdit which they can use.
If you use Expression Web to design your site, you can also use it to open the CSS file. Warning: if you use BlueGriffon, do NOT use it to open the CSS file, since it may mangle the CSS. In such a case, just use a plain text editor instead.
In the place where you will normally insert "background-image: url(mypicture.png);
", start by typing the
following instead:
Notice that the last character on that line is a comma. Do not omit that.
Open mypicture.txt
in a plain text editor. Since you already have your CSS file open in the
editor, depending on which editor you use, this will cause the file either to be opened in another
window or a new tab.
You will notice that the file contains numerous lines with letters, numbers, and the occasional "/" and "+". If you used the Windows "certutil" program, you will also see a line at the start of the file that says "-----BEGIN CERTIFICATE-----" and one at the end that says "-----END CERTIFICATE-----". Ignore these two lines. That is, do not copy them. They are not part of the image. Certutil includes them because it is primarily a program written to deal with SSL/TLS certificates, the stuff your site uses when it is accessed with HTTPS instead of HTTP. We're merely using its Base64 generation capability to convert images so that we don't have to download and install an extra program.
Copy each line from the file and append it to the end of the background-image
line. Do not leave
any space or create new lines. Although the Base64 encoded text in mypicture.txt
are separated
into many lines, join all of them into a single continuous line with no embedded spaces.
After appending the data, end the "background-image
" line with
That is, put a closing bracket (or "parenthesis" if you use a different variant of English) to match the opening one at the start of the line, and end the rule with a semicolon. I specifically mention this because it is easy to forget to do it after the long and arduous task of pasting the lengthy Base64-encoded line.
An example of the above code can be seen in the demo box below. Obviously, for your actual
background image, you should use something that is less "busy" and has very pale colours ("colors") so that
the background does not obscure the real content. I simply used my logo here because I couldn't be
bothered to design a special picture for something that was merely intended to give you an idea of what the
complete source code looks like. To view this sample code, use your web browser's
View Source function. For example, in Firefox, enter Ctrl+U, or Cmd+U on the Mac, to open a tab containing the HTML
for this page. The CSS code is near the top of the page. Look for the div#demo
selector in the
style
element.
This is just a demo of the CSS code. I made this text appear in black on yellow, otherwise you won't even be able to read it, since the picture below is seriously inappropriate for use as a background image.
If your image is in the JPEG format (with a ".jpg
or ".jpeg
" file extension), use
"image/jpeg
" instead of "image/png
". Likewise, if it is a GIF (with a
".gif
" extension), use "image/gif
". This string is technically known as the
MIME type, and it tells the browser the type of data that follows. Other less commonly used MIME types
(because they are supported by fewer browsers) include "image/apng
" (for .apng
),
"image/svg+xml
" (for .svg
), "image/webp
" (for .webp
)
and "image/avif
" (for .avif
). Do not invent your own MIME types: web browsers
will not understand it. Only use one of those listed above.
Note: if you are using a plain text editor that wraps lines automatically, disable that function. Otherwise it may reformat your extremely-long rule into multiple lines, possibly breaking your code.
Once you have finished the above, save the page and test it in a modern web browser.
Copyright © 2020 Christopher Heng. All rights reserved.
Get more free tips and articles like this,
on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.
Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.
This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.
It will appear on your page as:
How to Embed a Background Image in CSS to Get a Self-Contained Web Page