Much like the subject of the physics of light energy, the subject of graphics images is indeed a huge one. And if you have aspirations of becoming a graphic artist, a photographer, or a videographer, then this is the wrong course for you. As a web developer, your job is to basically write code for web pages. But as we have already seen, web pages that are all text and links to other web pages are boring in the extreme. So it is an essential skill to know how to incorporate elements of interesting fonts, colors, and images into your web pages to liven them up, and to make them look not only more interesting, but also aesthetically pleasing to the eye.
Graphics images come in many different types and categories, but basically they can all be boiled down to digital representations of photos, drawings, paintings, and animations. Video and audio files will be covered in a separate lesson. And it is important to make this distinction, because the actual original painting of the Mona Lisa is a lot different than a graphics file called mona-lisa.jpg, which is not paint on canvas at all. Instead, it is a digital file that contains a lot of ones and zeros that can be interpreted through software to produce a digital facsimile that fools your eyes into seeing an image of this highly recognizable painting. And of course any original Renaissance painting that is worth hundreds of millions of dollars deserves a much nicer frame than the one we used here, which was created simply with one quick-and-dirty line of code: border: ridge 22px gold;.
To download the code for this painting and its frame, simply click here. However, to view this project before bothering to download it, you can click here instead.
Just in case you don't know what a pixel is, you are looking at millions of them right now. A pixel is an almost microscopic square dot on your monitor display that can produce light in any one of 16,777,216 colors. If your monitor has a resolution of 1920 x 1080, that means that it has 1,080 horizontal rows of pixels that are 1,920 pixels long, or 1,920 vertical columns of pixels that are 1,080 long, depending on how you want to look at it (pun intended). Pixels are the units of colored light that make up the screen you are looking at right now. So if HTML is like a house, and inside the house lives a man named Mark Up, who has a head and body, then think of pixels as the biological cells in Mark Up's body.
In general, and not only in web development, there are two different types of images: raster images and vector images.
A raster image, like this JPEG file of the Mona Lisa above, is a series of pixels that are combined to form an image in a finite rectangular size. And that finite size is the most serious limitation of raster images, because you can always take a larger raster image and reduce its size, and it will still look just fine. But if you try to increase its size beyond the size of the original, the result will be a blurry, grainy, or pixelated version of the original image. The reason this happens with raster images is because the web browser knows how to subtract some of the pixels when it reduces the size of a raster image. However, it has to "fill in the blanks" so to speak, when you attempt to increase its size beyond what it was originally. In that case, your browser has to guess what color of pixel is required to bridge the gap between any two pixels that it knows are correct. And in reality, it's actually remarkable that it does so well with this task of guess and render! But the end result always ends up being a degraded image that is blurry, grainy, and pixelated. And the more you try to enlarge it, the worse the pixelation becomes. For instance, the Mona Lisa raster image above is 322 x 480 (i.e. — 322 pixels wide and 480 pixels high). So, you can always reduce its size to make it look smaller, but trying to display it at twice its original size (644 x 960) would make it look worse that it does at its original size or smaller.
Now it's time to prove our point. We actually have two Mona Lisa images for this test:
So, if the screen resolution of your computer monitor is not larger than a 4K monitor (3840 x 2160), then these four little tests will work just fine for you. The correct way to do this test is to click on each of the four tests below, one at a time. Each test will then open in a separate tab on your browser, and the title on each browser tab will identify each test. After you open the first test, you will need to click on the CSS Coding Course tab and then open the second test, and repeat this procedure until all four tests are open and identified on four browser tabs. Of course, if you click on the web page of one of those tests, that tab closes, so you will need to reopen that tab before continuing.
Once you get all four tabs open on your browser, it is time to compare the raster images there. Remember that the reason why we are doing these tests is to learn what happens when you resize raster images. Of course, the most striking comparison will be between Test 4 and Test 3. Test 3 is the Mona Lisa 1 image expanded in width from 322 pixels to whatever the width of your screen is. It will be very blurry and pixelated. That's what happens when you enlarge raster images beyond their original sizes. And the bigger you make them, the more pixelated they become. But Test 4 is the Mona Lisa 2 image reduced in width from 3840 pixels to whatever the width of your screen is. Reducing the size of a raster image generally does not degrade the image. In fact, this image is so sharp you can see every little crack and blemish in the paint, which is now over 500 years old! Now tell us how good you will look when you are over 500 years old! Anyway, clicking between the Test 4 and Test 3 tabs will let you view the differences in clarity, and that was the point of doing these two tests.
As for comparing the smaller images in Test 1 and Test 2, you will notice that there are three sizes of images represented there. The one in the middle is 322 pixels wide, the one on the left is half that size at 161 pixels wide, while the one on the right is twice the size of the middle image, or 644 pixels wide. Test 1 is actually a little bit shocking because the middle image looks better here than it does in the Test 2 middle image. But since it was made from an image that was exactly 322 pixels wide, that makes sense because we didn't have to expand or reduce its width at all. Nevertheless, if you look at the Test 1 image on the right, you will begin to see the beginnings of pixelation because this image was expanded to twice its original size. Test 2 images are here mostly just to compare against the Test 1 images. And the Test 2 image on the right shows the cracks in the paint that are blurry in the Test 1 image on the right, which is further proof of raster image pixelation.
So that brings us to the second most serious limitation of raster images, which is that it takes longer to load larger images than smaller images. Even though raster images are sharper when they appear on your screen, with a slower Internet connection, some people will get very impatient if they have to wait while large images download just to see your web pages. And so, a happy medium must be struck between outrageously large file sizes that look great but load slowly, and small files that load quickly but look terribly pixelated and blurry. It can actually become a very delicate balancing act when deciding which is more important in a raster image: better image quality, or smaller and faster-loading file size.
A vector image is an image that is mathematically drawn on your computer screen. And while it is completely true that screen pixels are required to perform such a task, the problems we have with resizing images goes away completely because each vector image is drawn to scale as soon as the browser is told the size specifications of the image to be drawn. The advantages of using vector images are speed, precision, scalability, and smaller file sizes. The disadvantages are that they are sometimes difficult to work with. If you snap a picture with your phone or camera, it is a raster image and may need only a few minor adjustments to make it ready to use on your website. But vector graphics images need to be designed and drawn digitally, and that requires artistic talent and skill, plus some great software to help you do it. For that reason alone, the vast majority of the images you will find on the Internet are indeed raster images.
But wait! We are not leaving this subject until we see just how speedy, precise, and scalable a vector image can be. Let's do a couple of tests similar to the tests we did with raster images.
Was that completely amazing, or what? The basketball images appeared instantly regardless of how large or small they were rendered. And the main reason why vector graphics images draw so quickly is that because have much smaller file sizes than raster images. A vector graphics file basically consists of a lot of precise drawing instructions, rather than a complicated bit map of colored pixels that must be rendered bit by bit, and pixel by pixel, like a raster image. But both types of images certainly have their place. For instance, a complicated photograph of people hiking down a trail in the forest lends itself perfectly to a bit map of colored pixels. If somebody wanted to convert that same bit-mapped raster image into a vector image, it would require drawing each area of pixels that are the same color separately. And there could be tens of thousands of such areas between all the green leaves on the trees, the flesh colors of each person's face, the colors of their individual pieces of clothing, and well... you get the picture (pun intended). Writing all of those tens of thousands of drawing instructions to create this image would be a complete nightmare, even for a complex computer program. And worse, even if it could be done, the smaller file sizes, and the faster, precise drawing speeds that make vectors so desirable would be lost completely. Therefore, the vector images you will end up working with will be things like logos that can be drawn quickly with fewer colors and easily and scaled to fit any size. In fact, only one graphics file type that we will talk about in this lesson will be a vector image type.
So now you are asking, "Then why did we spend so much time learning about vector images when we will see very few of them?" And yes, that's a very valid point and an excellent question. The reason is because other components you deal with in web development most certainly use vector graphics. For instance, PDF (Portable Document Format) files use vector graphics. That is why they look so nice, and scale up and down so well for both viewing and printing. Also, most computer font families are vectors, and that is why we can scale them up or down to any font size. In fact, each letter or character in a font family requires a specific set of individual drawing instructions to form that letter. And that is why a 10-point font looks just as good as a 100-point font. It is because each one is a scalable vector graphic. Try that with raster image fonts, and you won't be so easily impressed. There are other proprietary vector file formats that are used by Microsoft Windows, Adobe Illustrator, and CorelDraw, but we will only mention them in passing. The vector file format that lends itself well to web development, and that you will encounter most often, is called SVG (Scalable Vector Graphics), and we will talk more about that when we dive deeper into graphics file types.
When we start talking about raster image file formats, we cannot avoid the discussion of the two different types of raster image compression: lossy and lossless. And that discussion can be like jumping into a well; it can get very dark and murky the deeper you go. Since we only need to know about how this affects our final outcome (i.e. — the way the images looks on our web pages), we will jump through this hoop quickly, and avoid looking down too deeply into the well.
Now imagine if you will, that you are a professional photographer. You have the best cameras and photographic equipment that money can buy. Your printed photos hang in galleries and are sold for hundreds or thousands of dollars each, and you have even won awards for your work. The raw photographic images you work with are extremely high resolution and are millions of pixels in size. And that's a good thing! When you want to produce a large digital print of one of your award-winning photographs, every pixel counts in producing the final product: a large, beautiful, high-resolution, gallery-worthy digital print of your finest work.
But there is a problem. When you began putting these images on your website, it took minutes to load a page of your images. And customers complained about that and stopped buying your works. And even worse, some of them simply downloaded your images for free, and started making their own prints of your works much cheaper than you would have charged for the same prints. Bummer!
So let's take a moment to talk and image resolution. Image resolution is traditionally measured in PPI or pixels-per-inch. For web pages, 72 ppi has always been considered to be good enough for web pages. That is until just recently. With the introduction of Retina displays, there has been a tendency to use higher resolution images that are 150 ppi, or even 300 ppi. Also with more modern Internet download speeds, larger file sizes have become less of an issue. However, for printed materials that will be viewed at close distances like books, magazines, brochures, and photographs, publishers generally require 300 ppi images as the very minimum. However, for printed materials that will be viewed at a distance like posters and billboard, 150 ppi images are generally considered to be acceptable.
In order to make raster images that have smaller file sizes that will load faster on a web page, we use image compression. The computer algorithms that do the compression are not really important to us, as long as the images still look good on our web sites.
With lossy compression, many of the pixels that are part of the original raw image are removed. That may not change the look of the original image very much, but the result will be a much smaller file size of the JPEG image that you will then be putting on your website. The quality will be good enough that your customers can see how beautiful your photos are, but the images will not have the quality required to make duplicate digital prints from the preview images you place on your website. Two birds killed with only one stone required.
When creating JPEG images from raw images, your software (such as Adobe Lightroom) will allow you to choose how much lossy compression to use. And yes, some amount of photographic quality is compromised in the process. But as an artist, you have control over how much or how little compression you want to use. So you will want to find the happy medium between smaller file sizes that load faster on your web pages and still look great, and much smaller files that load really fast but actually look terrible on your web pages. If you are the photographic artist making the images, then you have control over both image quality and file size. If you are the web developer, then you must work with the images you are given by the artist.
There is also lossless compression, and that is used mainly by creating GIF and PNG images files. Yes, file sizes are reduced when you use lossless compression, but quality is not compromised. If you take a raw photographic image and create a GIF file from it, the number of colors used will be reduced from the 16,777,216 in the original to only 256 colors. That would certainly reduce the file size, but wouldn't it also reduce the image quality? The answer is that it might reduce image quality, but that would be due to the number of colors used, and not to the use of image compression. So maybe a better solution would be to take the raw photographic image and create a PNG file from it. Then the number of colors used will not be reduced from the 16,777,216 in the original, and quality will not be reduced by the use of image compression, but your file size will inevitably be larger than if you used lossy compression to produce a JPEG image.
Finally, we get to learn about the image file formats most often used in web development. Amazingly enough, there really only seven different image file formats here that we will talk about. They are the six file types of raster images: JPEG, GIF, PNG, WebP, AVIF, and ICO. And the one and only file type of vector images: SVG. There are some others like JFIF, which is basically a JPEG with a different file extension name, but let's avoid discussing JFIF images right now.
JPEG stands for Joint Photographic Experts Group. It is an image file format that has been around since the mid-1980s. And thanks to the explanations already given, we know that the JPEG image file format is probably the most popular one used on the web today. Since a JPEG is a raster image that uses lossy compression, file sizes are usually small so they load faster on a web page, which is their main selling point. The quality is usually pretty good, considering that they use some amount of lossy compression. But the quality of any JPEG will degrade each time the image is downloaded and edited. JPEGs use the full color palette of 16,777,216, which makes them ideal for displaying low-quality photographs. Take a picture with your phone, and most likely it is a JPEG image of a fixed size that is suitable for attachment to a text message, or to a post on a social media web page. The file we used at the top of this web page is called mona-lisa.jpg. You might see a JPEG image using other file extensions, but .jpg and .jpeg are the most common, and rarely you will see .jpe used. All three file extensions will be recognized by your web browser, and you will be able to preview each of them in VS Code, regardless of the file extension used.
In order to avoid a long discussion about MIME types, and about the JPEG standards of JIF (JPEG Interchange Format), JFIF (JPEG File Interchange Format), and Exif (Exchangeable image file format), let's just say that the MIME type for any JPEG file, regardless of the actual file extension used, should be defined in HTML as type="image/jpeg". But this should generally never come up, unless you are using a JPEG as a Favicon. And you can learn more about Favicons by clicking on the big button at the bottom of this page.
Lastly, you might see a JPEG with a file extension of .jfif, and that file is still a JPEG file, defined by default in HTML with a MIME type of type="image/jpeg", but VS Code may not allow you to preview it like it would allow you to preview any other JPEG file. Nevertheless, you can use it in your web pages as is, and your web browser will display it just like any other JPEG. Or, you can simply rename it with the .jpg file extension, and then VS Code will allow you to preview it. Plus, it will work just fine in your web pages just like any other JPEG as well.
GIF stands for Graphics Interchange Format. GIF is a graphics image file format that has been around since the late 1980s. It has a long history and has experienced several controversies over the techniques of dithering, the use of the web safe palette, and even the pronunciation of the GIF acronym itself. After all, how do you pronounce GIF? Do you pronounce it with a soft G like "JIF", a popular brand of peanut butter? Or like the soft G in "giraffe"? Or do you pronounce in with a hard G like the word "gift"? Or like the hard G in "gorilla"? None of that actually matters, but it gives web developers something to argue about when they aren't doing anything useful.
What you really need to know about the GIF image file format is that a GIF is limited to a color palette of only 256 colors, out of the possible 16,777,216 colors that are available. And that GIF files can be animated, which is their real claim to fame. And GIFs can also have transparent backgrounds, but that certainly is not a requirement for any GIF image, and yet that characteristic makes GIFs superior to JPEGs in that one way only. The reduced color palette makes GIFs inferior to JPEGs, which are capable of the much wider palette of 16,777,216 possible colors. But then again, the reduced color palette allows the GIF to reduce its file size, and that allows it to use lossless compression, which is yet another advantage over the JPEG.
But let's talk a little bit about dithering and the web safe palette. Remember that most of the image file formats we use today originated back when the World Wide Web was young. At the time, computer technology was somewhat in its infancy. Computer color monitors and the color graphics cards that produced color were both rather primitive compared to what we have today. The jump from CGA (which had a color palette of 16 colors) to EGA (which has a color palette of 64 colors) to VGA (which had a color palette of 256 colors) was considered to be leading-edge technology at the time. And so, the web safe palette was born as a standard, so that your computer would have the ability to display all 256 colors of any image that it displayed. That is perhaps the main reason why the GIF image format is limited to 256 colors. And the technique of dithering was one primitive attempt to get your computer to produce more from that reduced color palette through interlacing an image with transparent pixels. The result was usually a rather grainy, pixelated image of low quality. But it was considered to be a cutting-edge innovation at the time. Back then, GIFs were more prevalent than JPEGs because GIFs boasted their practice of using the "web safe" palette.
Now let's fast forward to modern times. GIFs are still very popular today, because of their ability to animate and have transparent backgrounds. This section starts with an GIF image that is both animated and also has a transparent background. That spinning globe image is called world-wide.gif. But think about it. People sometimes send animated GIFs as text messages on their phones because their phones contain a huge library of animated GIFs that are available at their fingertips. Sending an animated GIF is a lot easier than typing a long detailed message. So once again, a picture is worth a thousand words. And if you can't find an animated GIF that seems appropriate for that immediate situation, you can always download one in a jiffy from a website called GIPHY. We'll let you struggle with those pronunciations. Otherwise, let's just move on.
PNG stands for Portable Network Graphics. The PNG image format arrived about ten years after the GIF image format. It was designed as an upgrade or replacement for the GIF image format because it also had the capability to use transparent backgrounds, which was one advantage over the JPEG image format. And like GIFs, it also used lossless compression, which was yet another advantage over the JPEG image format. And like the JPEG, the PNG had the full color palette to use at its disposal. But alas, even though animated PNGs were possible, they were not supported by all web browsers. And that fact alone ensured the survival of the GIF image format as a long-term web standard.
But it is the combination of lossless compression and background transparency that really caused the PNG image format to soar in popularity. Since lossy compression often degraded the quality of a JPEG image, and the fact that a JPEG was unable to have a transparent background, plus the fact that GIFs could not use the full color palette, this was the winning combination for the PNG image format. About the only disadvantage was that lossless compression caused PNG files to be larger than comparable JPEG files which use a lossy compression algorithm. However, advances in technology have made the larger file size of a PNG a mostly moot point. With modern downloads speeds over the Internet these days, the time required to download and display a PNG image is negligible.
The image of three red cherries above is a PNG file with a transparent background, and it is called cherries.png. It scales down nicely from its file size of 1024 x 1024 pixels. But as you may recall, that's just the scalable nature of raster images, as long as you are scaling them down, rather than scaling them up.
WebP stands for Web Picture. Oh, but wait! That's too easy. Can't somebody invent a more obscure and hard-to-remember acronym? Nope! Guess not. You are stuck with WebP. And as computer technology changes, the standards that support it need to change as well. We really needed a new standard after all these decades of using only JPEG, GIF, and PNG images on our web pages. And Google decided to step up to plate to make that happen in April of 2018.
The WebP image format was designed to replace the three much older JPEG, GIF, and PNG image file formats, and was touted as such. And the WebP image format supports both lossy and lossless compression, the full palette of all 16,777,216 possible colors, including alpha channel transparency. And it is also able to support animation. Tests were performed between comparable JPEG and WebP image files using the same amount of lossy compression, and the results of these tests proved that the WebP files were actually smaller in size than the JPEG files without any noticeable reduction in image quality. These preliminary evaluations seemed to indicate that this new WebP image format was a win-win for all parties concerned.
Nevertheless, adoption of the new standard has been much slower than anticipated. While some have rushed to quickly adopt WebP as their new de facto standard, others have dragged their feet and continue to use the old school image formats, with which they are already most familiar. Therefore, it may take time for WebP to be fully embraced by photographers, graphic artists, and web developers alike.
This WebP image of a leucistic axolotl in an aquarium is named axolotl.webp and its full dimensions are 1280 x 960 pixels in size. Nevertheless, scaling it down does not seem to compromise the quality of this raster image. Web developers can therefore see a very bright future for the WebP image format.
AVIF stands for AV1 Image File. And along with Google's WebP format, AVIF is yet another new kid on the image format block, while the other image file formats we've talked about have been around for a very long time. AVIF was released in 2019 by the Alliance for Open Media, an organization that you are probably unfamiliar with. The main claim to fame for the AVIF file format is that it can greatly reduce the size of the file with much less loss during compression, and yet it can still produce a sharp image for viewing. However, the industry has been slow to adopt the AVIF format, even though it has been readily supported through all major web browsers. That means that you might find AVIF files in use on the web, even though most image editing software programs have been slow to support it. AVIF transparent backgrounds in particular seem to lack support, even though the specifications make claims to the contrary.
This AVIF image of a scarlet macaw is named parrot.avif and its full dimensions are 1000 x 667 pixels in size. Nevertheless, scaling it down does not seem to compromise the quality of this raster image, despite having a compressed file size of only 41 kilobytes.
And despite the remarkability of this feat to compress an image file and still produce a fine quality image, until AVIF files are more widely adopted, we will not spend much more time on them here. However, if you find that you are more interested, we suggest that you visit the websites linked below to learn more. A good blog discussion that compares the differences between WebP and AVIF file formats can be found here. And since many of the image editors available do not properly support the AVIF file format yet, you may find the image editing tools here to be useful.
The last raster image format we are going to discuss is the ICO image format. And although most web browsers will display an ICO image if it appears in the body of a web page, that's not really the desired purpose for an ICO image. The ICO image was originally designed to be displayed as a favicon next to the title of a web page, as displayed on the browser tab. And the favicon and title are supposed to be coded in the document <head>, not the document <body>.
Modern favicons can be of any image format type these days, not just the ICO image format. ICO files are generally supposed to be small, but they will be scaled down to fit on the browser tab, regardless of their actual physical dimensions or file size. ICOs also support transparent backgrounds. And if you want to see an actual ICO file in action, look no further than the favicon on the browser tab of this web page. That ICO image is named favicon.ico, and it has a MIME type of type="image/x-icon", even though a PNG image is used as a favicon on almost all the other web pages of this website. And now, there isn't much more to say about ICO image format types. However, if you want to learn more about favicons, please click on the big button at the bottom of this page.
SVG stands for Scalable Vector Graphics. The SVG image format is the only vector image format supported by most web browsers. Since we already spent a great deal of time talking about vector images earlier, we will try not to become too repetitive. The very nature of vector images makes them highly scalable without any sacrifice in image quality. That is because SVG images are basically a set of drawing instructions, rather than the rectangular bit map used by raster images. They can also support transparent backgrounds. And the full color palette is also available to SVG images. SVG images also lend themselves well to lossless compression.
The one thing that was not mentioned before is that these drawing instructions we speak of are actually written as an XML (eXtensible Markup Language) text file. For that reason, the MIME type of an SVG file is defined as type="image/svg+xml", which is important if you intend to use an SVG image as a favicon. Lastly, the image of the basketball above is named basketball.svg, and you might remember how incredibly scalable that vector image was when we did our vector image testing earlier in this lesson.
Now that we have a solid knowledge of images, let's start writing HTML and CSS code to display these images on our web pages. But before we can do that, we need to know that there two ways to display images. We can display images in the foreground, or we can display them in the background. A foreground image must be coded in HTML, while a background image must be coded in CSS. And regardless of whether an image is in the foreground or the background, the CSS styling rules for both kinds will obviously be coded in CSS.
By now, you've seen lots of <img> tags. And any time you use one of these tags in the document body of your HTML file, you are coding a foreground image. That means that it will be on top of, and in front of, anything that is in the background, like a background color, or a background image. And of course, you remember clearly that <img> tags do not require closing tags. However, they do require that you specify the source file of the image, and we add that inside the tag itself. For example, <img src="mona-lisa.jpg"> will put the image file called mona-lisa.jpg on your web page. And then, after it is there, you will style it through CSS. Simple, right?
When using the <img> tag, there are a couple of other attributes you should know about besides the most obvious one: src. And you also need to know about the default CSS display property for <img> tags.
Actually there are several properties you can specify inline inside your <img> tag, but we are only going to talk about three of them here. We recommend using the alt attribute, and sometimes the title attribute, even though both attributes are optional. Of course, the src attribute is not optional. Otherwise, what would be the point of using an <img> tag?
A typical and properly-formed <img> tag should look something like this:
<img src="mona-lisa.jpg" alt="The Mona Lisa" title="by Leonardo da Vinci">
We already know what the src attribute does. The alt attribute is there for two reasons. The first reason is to provide text for the user to see if the image does not appear for some reason. Perhaps the web developer used the wrong src attribute for the image. Or perhaps they forgot to upload the image to the website. Regardless of the problem that prevents the image from appearing, the alt attribute will be displayed where the image should have been to tell users what that image was intended to be.
But there is also a second reason to use alt attributes, and that is to provide descriptions for people who are blind or sight-impaired. People with these disabilities still need to use their computers, and that requires the use of screen reader software. It's actually rather fascinating to watch someone who is blind use their computer. Everything you see on the screen as a sighted person must be found through audio cues by the blind person. The screen reader reads the text on the screen, and a voice synthesizer enunciates the words for the blind person to hear. Should there be any images on the screen, the screen reader is required to describe what each image is, and that can only be done through the text it finds inside the double-quotes of the alt attribute. In fact, making sure that websites are ADA-compliant is actually a very important job that pays well. It is indeed a specialized field that can be quite rewarding in ways beyond merely receiving a big paycheck.
The title attribute is different than the alt attribute in that it shows the text inside the double-quotes when the user hovers their mouse over the image. Some coders simply choose to make the text inside the alt and title attributes the same, but knowing what purposes they serve can be very important. Yes, the sighted person can easily see that this is a painting of the Mona Lisa by Leonardo da Vinci. They don't really need your explanation, but thank you very much anyway. On the other hand, an unsighted person would be very grateful to hear what that image is all about. Please close your eyes for 30 seconds and imagine what your life would be like without the ability to see 16,777,216 colors, and pictures of beautiful landscapes and works of art. And then you might find yourself adding much better descriptions inside the double-quotes of your alt attributes. Enough said on that subject.
Of course, it doesn't end there. There are more attributes and CSS styles you can add to your img tag inline. In fact, if you were going to add a class or id, you would probably want to add that before the src attribute. Why? For the same reason that you wouldn't hang the Mona Lisa on the wall without its frame. Any CSS style rules that apply to each particular image probably need to be applied first. It's like telling someone, "Hey! Put that picture in its frame before you hang it on the wall." Also, we believe that all CSS style attributes (such as width and height) are best defined in an External CSS stylesheet, rather than inline. As a best practice, we reserve the use of Inline CSS as a "last resort" when all other ways to style an element have failed.
And while we are on the subject of CSS style, it is important to know about the Default CSS rules are for <img> tags. And the first thing to know is that the width and height of any raster image will default to the actual size of the original image. For instance, an image that is 1000 x 1000 pixels in size will continue to be that size, even if you try to contain it inside of a div with a width and height of 500 x 500. So for that reason alone, you will often see Reset CSS rules of img { width: 100%; } to prevent any image from being larger than its container. Vector images can behave differently. They will sometimes default to 100% of the size of their container if the size is not restricted by specific width or height CSS rules.
And as a general recommendation, another best practice is to style either the width or the height of an image, but not both. If you change on;y the width of an image, the height with scale proportionally and automatically to prevent stretching and distorting the image in any way. And the same is true if you change only the height of an image: the width will automatically scale proportionally. But changing both can have the serious and unexpected side effects of stretched and distorted images. And if an image does not fit nicely inside its intended container, then change either the width or the height of that container accordingly.
Another important thing to know about the Default CSS rules for the <img> tag is that the display property of an <img> tag has a value of inline-block by default. You may recall from earlier discussions that inline-block is a combination of the inline and block values for the display property. You may also recall that Default CSS rules take precedence when no other rules are defined. So this can sometimes cause a few unintended consequences for us in terms of the behavior of our images. The inline part of inline-block means that images will align themselves horizontally, whether that was our intention or not.
A complete noob will simply add a <br> tag at the end of each <img> tag to prevent this from happening. And while that certainly works, the more elegant way to fix it in CSS is by changing the display property to a value of block, as in display: block; which forces each image to be on a line by itself, regardless of the width of the image. Another way to fix this behavior is by placing each image inside of a div with an id or a class.
Isn't it amazing that there is this much to know about the "simple" <img> tag? Let's move on.
Background images are coded much differently than foreground images. And that is because they need to be coded through CSS so that they will remain in the background behind other foreground elements, like the headings, paragraphs, and maybe even the foreground images that we put in the document body of our HTML file. Any code we use to style background images will also be part of the CSS stylesheet as well. For example, if you put background-image: url(bricks.jpg); inside the body { } rules in your CSS stylesheet, then a tiled background of bricks will most likely be the result, depending on the size of the image you are using. Because, if a background image is smaller than your screen width, then it will repeat itself both horizontally and vertically, depending on the other CSS rules you include.
Let's take a look at an example to better visualize what we are talking about here. Click on the following link to see an example of a tiled background: A Tiled Background Example
Isn't that amazing? The artist who created this image designed it so that it could be easily tiled. All of the edges are meant to mate up seamlessly with the opposite edges of the image. And this is the result. The actual JPEG image used is 451 x 288 pixels in size. And below is what that bricks.jpg image looks like untiled.
Notice that on the tiled background example, the image repeats itself multiple times, both horizontally and vertically, until the entire background is covered with bricks. To get a better idea of how many times it repeats, one of the bricks has a white spot of mortar on it. Look for that white spot to count how many tiles there are in both directions. One last thing to notice is that the tiles don't have to be the exact size to fit your screen. Any tile that is too long to fit the space, either horizontally and vertically, is "trimmed to fit" just like any floor tile, wall tile, or sheet of wallpaper in real life. And CSS knows better than to include any unnecessary horizontal and vertical scroll bars, because background images are used for decoration purposes only.
To download the project code for this project, simply click here.
Yes, but what about those big background images that cover the entire web page? That's a great question! Aren't you glad you asked it? For those full screen images, we certainly don't want CSS to tile them. One background image will be plenty, thank you! Let's look at another example that uses a full screen image: The Stone Bridge Background Example.
To download the source code for this project, simply click here.
Actually, there is a lot going on in this example. We use this project to teach lessons about other subjects, so just ignore all of that stuff on the left side of the screen. Instead, let's concentrate on the stone bridge image in the background.
One thing that you might find interesting about background images in general, is that the size of the image you use does not have to be the exact same size as the screen that the web page is viewed on. However, it is important to remember from our lesson on raster images that reducing the size of any image does not degrade its quality, but enlarging it beyond its original size definitely does. And the more you enlarge it, the worse the degradation becomes. This obviously applies to foreground images and background images alike. The main point here is that it is best to start with an image that is wider than the width of the screens that most people use to view web pages.
So now let's look at the code behind this stone bridge. These CSS rules are part of the body { }
Of course, the first line above indicates which file we will use for our background image. And just so you know, url stands for Uniform Resource Locator. On the second line, we tell CSS that we don't want the image to repeat either horizontally or vertically, like it did when we created our tiled background. CSS likes to repeat background images by default. And just for the sake of reference, the actual image size of the-stone-bridge-of-arta.jpg is 1920 x 1080 pixels. And this is important because on the third line, we tell CSS to cover the width of the screen with this image. And we could have just as easily told CSS to contain the image. Sometimes it seems like a balancing act between cover and contain. And it all depends on which method works best in each situation. We often use the trial-and-error method to determine which one to use, because cover tells the browser to make sure the image covers the entire screen (or container), even if it has to stretch the image or cut off part of the image along one of the edges. However, contain tells CSS to always show the whole image, even if that leaves some space on one of the sides or the bottom. Lastly, the third line tells CSS to set the height to 100% of the viewport height. We could have said 100% instead of 100vh, but there are very good reasons why we should be using viewport height which we will explain in better detail in a future lesson.
So far we have learned that background images can be tiled or full screen, but they can also be placed inside of divs. Let's take a look at this project called Eight Planets just to see what we are talking about here.
Let's also download the project in the form of a ZIP file, so we can unzip it, and then view the project code after we open it in VS Code. In the HTML code of this example, we have a container div with a class called planets. And inside of that div, we have eight nested divs, with two class names for each one. One class name is called planet and the other is called p1, p2, p3, p4, p5, p6, p7, or p8. And looking at the index.html code should make this concept pretty easy to understand. Of course, the class names of planets and planet are completely different. The div called planets is the container div that holds the other eight nested divs, which all share the same class name of planet, but they also include a second class name to "identify" each planet individually.
Yes, there are a couple things to know about that second class name. First of all, if we are using it to identify each class separately from the others, why not use an id rather than a class? After all, it is unique and used only once. And actually, that's a very valid point. The answer is one of laziness actually. It is simply easier to type <div class="planet p1"> than it is to type <div class="planet" id="p1">. And besides, there is no CSS rule against using the name of a class only once, even though using the name of a unique id more than once is definitely a no-no.
OK, fair enough. Well then, why not just type <div class="planet 1"> instead of <div class="planet p1">? There are eight planets. Why not just give them numbered class names? Another great question! The reason for that is because, even though HTML doesn't mind numbered class names, CSS strictly forbids it! In CSS, a class or id must start with a letter, a hyphen - or an underscore _ but it cannot start with a number.
Alright then. Well, why bother having two classes for each nested div? Wouldn't one class for each be easier and simpler to deal with? Right again! To HTML, it would be simpler. But to CSS, that would require writing a whole lot more code. Let's look at the style.css external stylesheet for a moment. Starting on line 39, the class of planet has all of the code that is common to all eight planet divs. But the only thing that makes classes p1 through p8 "unique" is the actual file name of the background image that we will be using for each planet. And so, if we were to use only one class name for each of the classes p1 through p8, then we would be forced to include all of the common code that is currently in class planet for each and every one of those other eight classes.
So... what's up with the images/ in url names like background-image: url(images/mars.png); anyway? Another good question. We have eight planet images and a favicon image, and all those image files were just cluttering up our project, so we moved all nine of them into a folder called images, and we need to add the name of that path to the url when we point to that file name.
Lastly, it is hard to see where the boundaries of the planets div and the planet divs are, so on lines 36 and 46 of the style.css file, you will find a couple of border CSS rules that you can uncomment, and that will allow you to see where all nine of those divs exist in the overall scheme of things. As you may recall, we sometimes use borders to help us locate where our divs begin and end. And we've always found this technique to be especially helpful when working with nested divs.
So before we wrap up the subjects of that last two parts on Colors and on Images, and even though we've already talked a lot about Backgrounds, we have one more quick project for you to look at. Yes, we know that almost any element can have a background, and that includes the HTML document itself, the HTML body, almost any container div and/or any nested div inside of any other div. But in this Backgrounds project. we are going to see nine different types of backgrounds, even though we've already talked about several of these background types.
Almost all of the projects we've seen so far have a background-color minimum, if not something a little more fancy like a brightly-colored linear-gradient or a radial-gradient. But we've also seen how a background-image can be used as well. We've seen an example of a tiled, a covered, and a contained background-image. And we should know how a background-image can be aligned to the top, middle, or bottom of its parent container. We can even use an animated background-image. We can also use a looping video file as our background, if we use the correct HTML settings and CSS style rules. Click on the following link to download the Backgrounds Project Code. Please feel free to explore the code in this project on your own.
Before we end this rather lengthy discussion about images. we would like to briefly discuss the topic of legality. We consider it to be a best practice to always make sure you have the legal right to use any resource on your web pages, and that certainly includes image files. Yes, it is true that modern search engines offer us a great many graphics images that can be downloaded for free. But there are often legal obstacles attached to their use on your web pages. Knowing the differences between material that has a copyright and material that is allowed for fair use should always be one of your highest priorities before using any graphical image, video, music file, sound effect, or even a paragraph of text that you did not write yourself. Although it is rather boring to read, the Harvard Office of General Counsel does a great job of explaining the legal definitions concerning copyrights of intellectual property and fair use.
Without providing free advertising for them, we should mention that you will find that there are websites that want you to pay for the images they offer. And if you download their images without payment, they sometimes have watermarks embedded into the images that will readily identify illegal use. Therefore, if you find watermarks on any image you download, do not use that image under any circumstances. You might get away with using it, but if your website is on the internet, and visited by hundreds or thousands of people, the chances of getting sued increases significantly. In most cases, if you use an image without permission or proper attrition, you will probably not get sued. But the plaintiff could contact your web provider and demand that your website be taken down until you come into full legal complicance.
So what's a web developer to do? Web pages without images can be very boring, so it is highly desirable to be able to include images on your web pages.
The good news is that there are lots of graphics artists and photographers out there who want to be recognized and who don't necessarily expect to make a lot of money from people who use their images or photos. In those cases, they may simply ask for attrition which means that you simply acknowledge the artist or photographer somewhere on your web page with text like Used by permission of John Doe. And there are lots of free images available to you that are clearly in the public domain. Click on any image you find on Wikipedia and you will find a blue button in the lower right-hand corner of the resulting web page that say More details. If you click on that button, a page that explains all of the available sizes of each image are there, as well as all of the legal mumbo-jumbo about using this image. Oftentimes, it will say that you are free to use the image without attrition or advanced permission. It might also say that you are free to remix or edit the image in any way that you see fit.
And well beyond Wikipedia, there are lots of websites out there that offer you free images to download, modify, and reuse, or for a small monthly or yearly fee. Almost every image you find on this website was already either in the public domain or reused by permission and without attrition. This isn't rocket science! It really isn't that hard to stay legal on the World Wide Web! Oh, and speaking of rocket science, did you know that 99.9% of the images on the various NASA and JPL NASA websites are 100% free and in the public domain? Yes, it's true! You paid taxes for these images, so basically they belong to you. Anyway, we hope you find this information to be helpful. So stay legal! That's always the smartest way to go.
We covered a lot in this lesson. Let's quickly review everything we learned. We now know what pixels are, and what is meant by screen and image resolution. We also know that there are two types of images: raster images and vector images. We also learned what happens to a raster image when we reduce or expand it from its original image size. We also know why the same is not true for vector images. And we discussed image file formats and the two methods of image compression, which are lossy and lossless. We also learned about the five main raster image types we use in our web pages: JPEG, pathGIF, PNG, WebP, and ICO. And we learned about the characteristics of each raster image type, and the advantages and disadvantages of each one. We also learned about the only vector image type that we use on the web: SVG. But we also have a better understand of other vector technologies, which will be important when get into our discussion of scalable fonts. We also learned about foreground images, and how they are coded in HTML in the document body, and styled through CSS. That also means that we had to learn the basics of the <img> tag, including the src, alt, and title attributes. And we learned about how the alt attribute helps us to make our web pages more ADA-compliant, and beneficial to blind and sight-impaired people. We also learned about the Default CSS properties of img tags, especially the display property and how to deal with it. Also, we learned about background images, which are coded and styled entirely in CSS. We saw three different examples of background images: tiled background images, full screen background images, and background images inside divs.
Maybe all of that seemed like it was a lot to learn. And granted, it certainly was. But believe it or not, we only scratched the surface. There is a lot more to learn that we mostly skipped over for the sake of convenience. For example, what do you do if you have a JPG image with a white background, but it needs to have a transparent background? Or, what do you do if you have an image with a cluttered background, and you would like to have that background removed completely? These are all problems that a graphic artist would need to deal with, and we only explained images as used by the web developer. For now, please be content that you have a basic understanding of images, and how to display them on your web pages.
Before continuing on to the next lesson, you should probably take a look at this side tutorial (linked below) on Titles and Favicons, especially now that we have discussed image file formats completely. Having both a title and a favicon on each web page will make your web pages look a lot more attractive and professional.