Choosing and optimizing images for the background and foreground using HTML and CSS.

Introduction

Valley Morning 37 original abstract landscape oil painting on Clayboard panel by Pam Van Londen.
Images can be added to apps/sites in the foreground (in the HTML), in the background of blocks (in a stylesheet file), or as borders (in a stylesheet file).

The main purpose of optimizing images for online viewing is to reduce the time it takes a browser to display an image file in its correct size. Visitors to web sites do not want to wait for photos and other graphics to load; they want instant reading and viewing. Updating the dimensions of images to fit within the scroll area of a browser is also helpful because visitors want to view an entire image in one glance without scrolling around to see it. And they don’t want graphics to overlap other important information on the page.

In addition, web site servers around the world would fill up too quickly if we all loaded large graphic files onto them because we were unskilled at reducing the file size. To keep from filling up our allotted server space, we will reduce the file size, dimensions, and resolution, and save in the proper format. These concepts are explained in the Specifications tab.

Each graphic or photo has an optimal file format based on the imagery in that file. We’ll review that in the Examples tab.

Recent improvements in display resolution have altered the sizes acceptable for use on the Web. High-resolution Retina displays need higher-resolution images, while phones, which use up data bandwidth, should receive lower-resolution images. Allowing the browser to detect and serve up the correct file will save bandwidth.

Online Image Specifications

This photo was saved in the proper file format at the exact dimensions needed for display, with a small file size, and a descriptive file name.
This photo was saved in the proper file format at the exact dimensions needed for display, with a small file size, and a descriptive file name.

Optimized images meet these specifications:

Descriptive file name
To improve search engine optimization (SEO), file names should include who, what, when, and where as much as possible. In other words, use descriptive but concise file names. For example, a picture of a German Shepherd puppy playing with a ball needs to have a file name like this: german-shepherd-puppy-ball.jpg. This will help search engine bots to categorize it for users who are searching for related images.
Small file size
Reduce file sizes to as small as possible for the fastest load time. Serve high resolution images only to high resolution devices. This is typically done using the srcset="" and sizes=""attributes. Refer to What is image compression? Lossy compression uses approximations to discard some of the image data, which can result in pixelation, while Lossless compression does not degrade the visual quality.
Exact dimensions
Crop and reduce the size of images to fit the dimensions of the space in your web page. Serving an image 8000px wide when it will only fit in a 600px wide block will load very slowly.
Correct file format
Online photos are usually .JPG.
Line-art images like logos and icons are usually .GIF and sometimes 8-bit .PNG.
Graphics with true transparency need 24-bit .PNG.
Reduced resolution
Monitors render between 72 to 300+ pixels per inch (ppi); the typical default is 72ppi. Much higher resolutions are available now, so providing multiple image sizes for each is becoming a standard. Read more about resolution from Adobe.
Color Mode
RGB for .PNG, .JPG, .SVG, and .WebP, and Indexed for .GIF (and sometimes PNG).

Example File Formats

The most common file formats for the web are .GIF, .PNG, and .SVG for line art, and .JPG and WebP for photography.

These files are optimized at 150px wide in RGB color mode at 72ppi (pixels per inch). Notice which letters, shapes, imagery are clear, blurry, or pixelated.

Example of an SVG file
SVG Scalable Vector Graphics are mathematically-derived and marked with XML for two-dimensional, interactive, or animated images. Notice how crisp the text is compared to the other file formats. (File size is 15k.)
Example of a gif file
GIF files can have 8-bit transparency and/or animation and are typically used for line-art graphics. Their edges anti-alias to just a single background matte color. A common trend is to save short photo/video sequences as animated .GIF. GIF files are saved in Indexed color mode. (File size is 6k.)
Example of a png file with transparency
PNG files have true transparency (alpha channel) and are usually best for biomorphic shapes and line art, and solid colors. They can be placed over any variety of colors without distortion and the background shows through any blank or transparent areas. The color mode is typically RGB but can also be compressed in Index color mode. (File size was 9k but compressed to 3k.)
Example of a png with transparency over a photo
PNG files have true transparency (alpha channel). If the compression software does it's job well, even a photo with line art can be in .PNG format, however, the photo is pixelated. (File size was 74k but compressed to 13k.)
Example of a jpg file
JPG files are only used for photographic images. Photos typically have millions of colors, great detail, and are taken on high-res cameras, so the file sizes are too big for the web. Resizing and compressing them reduces the load on the web serve. They compress down to small file sizes and remain rectangular. This file was saved from Google Drawings with excellent compression. Higher compression reduces image quality. (File size is 10k.)
Example of a WebP file
WebP files are typically only used for photographic images. They compress down to small file sizes and remain rectangular. Higher compression reduces image quality. Transparent backgrounds are possible with an alpha channel. (File size is 24k saved from a 107k JPG file.)

The following table illustrates the same information:

Image file formats and their features and purposes
Format Photos Screenshots Line-art Animation Transparancy
JPG * *
WebP * * *
PNG * * * *
SVG * * *
GIF * * * (one color)

Production Process

This tab includes basic information about resizing and compressing. Choose from these tools to accomplish the task once you've chosen some images: Take Screenshots | Local apps | Online services | Node module.

  1. Choose photos, screenshots, diagrams, etc. and produce the sizes you need for your assignment. Add them to a folder on your hard drive to keep them organized.
  2. Rename the files with hyphens to describe their imagery; something like this:
    • first-lastname-self-portrait.jpg
    • db-relationships-users.png
    • expo-2022-poster-cloud-app.png
    • oregon-coast-lava-flow.jpg
    • turtle-tessellation.png
    • python-drinks-shop.png
    • matplotlib-weather-data.png
    • periodic-table-melting-points.png
  3. Determine the necessary dimensions for each image based on where they will be placed on the page. What are the maximum widths and heights needed to fit those spaces? They should be small enough to view the details but not so large they load slowly. Resize using the one or more of the apps noted below.
  4. Export or save the file in the most appropriate format.
    • Export or Save a photo as .jpg or .webp for a background or foreground image.
    • Export or Save a line drawing as .png, .gif, or .svg for a foreground image.
  5. Copy the optimized images to an images folder in the website workspace folder. If you are working in a framework like React, then the images folder can be placed in the src or public folder.

Take Screenshots

Take a cropped screenshot of just the important part of your imagery. Don't include the background of your Desktop/Finder or other folders/files. Crop closely to the imagery you want users to read.

Example Screenshots

Here are examples of good screenshots versus poor screenshots of code:

Plot of Walla Walla temperatures generated with Python and MatPlotLib.
Good Example of output: Plot of Walla Walla temperatures generated with Python and MatPlotLib. File size is 8k at 350px wide saved in PNG format.
Plot of Walla Walla temperatures generated with Python and MatPlotLib was not cropped closely, so is too big.
Poor Example output: Plot of Walla Walla temperatures generated with Python and MatPlotLib was not cropped closely, so is too big. File size is 85k at 600px wide saved in PNG format.

After zooming in on a portion of the code, the screenshot was cropped closely.
Good Example of input: After zooming in on a portion of the code, the screenshot was cropped closely. File size is 24k at 1102px wide saved in PNG format.
The screenshot was not zoomed in on or cropped.
Poor Example of input: The screenshot was not zoomed in on or cropped. File size is 16k at 600px wide saved in PNG format.

Local applications

The process of cropping, resizing, and exporting can be done with a variety of apps on your hard drive. To resize, find the menu related to Image Settings. Choose to maintain the aspect ratio.


Use I❤IMG to upload, rename, set the width, and click the Resize button. Download the .zip archive.
Using I❤IMG, upload, rename, set the width, and click the Resize button. Download the .zip archive.

Online Resize and Compression Tools

A quicker way to optimize a group of files for a simple website is to use an online service such as I❤IMG which has resize and compression tools.

  1. Choose the I❤IMG images tool.
    • Click the button and choose the .JPG and .PNG files you need from your folder of images.
    • Choose the ⚙️ gear icon to adjust the width of each to between 400px and 600px. Click the "maintain aspect ratio" and "Do not enlarge" buttons. The width you choose can be adjusted to help lower the resulting file size.
    • When ready, click the button, then the resulting .zip archive.
    • Unzip the resulting .zip archive of PNG files.
  2. Drag those new files to the I❤IMG images tool to reduce the file sizes. The files will be roughly 75% smaller, which means your images will render quickly.
    • When ready, click the button, then the resulting .zip archive.
    • Unzip the resulting .zip archive of PNG files and move them to your images folder.

Node Sharp Compression (0ptional)

This content is not required reading.

Using Sharp for Node.js's asynchronous functions for resizing images with sharpen and output to .jpeg format, I optimized 3 somewhat blurry 7.5Mb-sized photos of artworks. The script resized the images from roughly 2540px square to exactly 400px square using a sharpen sigma setting of 1 and a jpeg quality setting of 98, which resulted in a clearer image and much smaller file size.

Notice how...

The original images on the left load much slower than the compressed images on the right:

From Stanley Ulili at Digital Ocean: How To Process Images in Node.js With Sharp, which references High performance Node.js Image Processor.

 

Foreground Images

This tab includes basic information about HTML and CSS for images:
Image tag | Responsiveness | Galleries | Flexible Gallery

The simplest way to mark an image in a web page is with this self-closing tag. It includes the source, alternative description, and width and height:

<img src="" alt="" width="" height="" />

Alternative text is a description of the imagery, which is read to people listening to the web pages (rather than reading them with their eyes). Many people are colorblind, visually impaired in other ways, or are completely blind. They rely on hearing the descriptions in order to understand the context. It would not be fair to them if they missed vital visual information. Here is an example of alternative text from one of the images provided in the previous tab's gallery:

<img 
   src="gallery/pvl-valley-storm-1.jpg" 
  alt="Valley Storm 1, an 8x8-inch oil painting depicting a storm with a valley, clouds, and mountains." 
/>

Longer descriptions with more adjectives can be helpful.

Many properties can be added to image selectors in a stylesheet, including width, height, border, margin, padding, box-shadow, transform, transition, clip-path, etc.

If you don't specify the width and height in the HTML tag, then you can do it in a stylesheet: rule (which we learn about later):

img {
    width:;
    height:;
}

When an image is wrapped in an anchor:

<a href="" alt=""><img src="" alt="" /></a>
...its default blue border can be removed or changed in the stylesheet. The zero turns off the border's width:
a img {border:0;}

Responsiveness

An important aspect of images for the web includes making them responsive to different devices. That might mean adjusting the dimensions, quality, and/or file size. For example, depending on the width and height of the screen displaying the image, we can add the srcset="", sizes="" attributes, so the browser can serve the one it needs, like this:

<img 
    src="images/descriptive-name-320.jpg"
    alt="Description of the imagery."
    title="© 2022 ownername"
    srcset="img/descriptive-name-320.jpg 320w, img/descriptive-name-640.jpg 640w, img/descriptive-name-1080.jpg 1080w"
    sizes="(max-width: 480px) 100vw, (max-width: 900px) 33vw, 254px"
/>

If different orientations, or completely different images are needed, then using the picture element is recommended:

<picture>
    <source media="(min-width: 900px)" srcset="photo-vertical.jpg" />
</picture>
<picture>
    <source media="(min-width: 750px)" srcset="photo-horizontal.jpg" />
</picture>
<picture>
    <img src="photo.jpg" alt="" />
</picture>

Using srcset="", sizes="", or <picture> is not recommended for CS 290.

Learn more:

Galleries of images

Sets of images and other media are referred to as galleries. These galleries also need to remain responsive, so users don't have to scroll sideways, as well as up and down, to see each image, video, or document clearly.

A simple method of creating a gallery is to use sets of <figure>s, which are coded like this:

<figure>
    <img /> or <iframe></iframe>
    <figcaption>description</figcaption>
</figure>
 

Then, in a stylesheet, rules are defined for those tags so they fit the page layout:

figure {
    margin:__; 
    padding:__;
    width:__px;
    border:__ __ __;
    }
img {
    width:100%; 
    margin:0; 
    padding:0;
    }
figcaption {
    font-size:;
    text-align:;
    display:block;
    padding:;
    }

Flexible Gallery

Example of a responsive gallery made using display:flex.
The required method for this course incorporates display:flex and flex-flow: row wrap. View it in action. (Video included.)

Another approach, which is required for CS 290, is to use a responsive, flexible method using a class="", <figure> blocks, and stylesheet property: display:flex:

<article class="gallery">
   <figure>
      <img /> or <iframe></iframe>
      <figcaption>description</figcaption>
   </figure>
   <figure>
      <img /> or <iframe></iframe>
      <figcaption>description</figcaption>
   </figure>
   ...more sets
</article>
Then, in the stylesheet, define that class along with the other three selectors.
.gallery {}
.gallery figure {}
.gallery image {}
.gallery figcaption {}
The required method for this course incorporates display:flex and flex-flow: row wrap. View it in action. (Video included.)

Other gallery methods not allowed in CS 290 include:

Background Images

Images can be declared in the background of most HTML blocks. The two most common are placed in the body {} and header {}.

Eight different properties can be used for background, including image url, position, size, repeat, attachment, origin, clip, and color.

Colors can be combined with multiple images to create unique effects.

This rule includes the URL of an image for the background of the body element:

body {background-image: url(path/to/file.jpg);}

By default, a background graphic will repeat on the x and y planes. We can turn off one or the other with repeat-x or repeat-y, like this:

body {
    background-image: url(path/to/file.jpg);
    repeat:repeat-x;
}

And to display it only once, use no-repeat, like this:

body {
    background-image: url(path/to/file.jpg);
    background-repeat:no-repeat;
    }

To display more than one image in the background of a block, we specify values for each, separated with commas, like this:

body {
    background: url(path/to/file.jpg), url(path/to/second-file.jpg);
    background-repeat: no-repeat, no-repeat;
    background-position: top right, bottom right;
}

The repeats and positions can be altered for each image in the order each is specified.

Photo covers the background of a page.
A photo covers the background of a page and the main block is slightly transparent, so it shows through, but does not reduce readability or legibility.

A design trend is to cover the entire body with one large photo that is fixed while the visitor scrolls. This can be accomplished with:

body {
    background: url(path/to/file.jpg);
    background-size: cover;
    background-attachment: fixed;
    background-position: top left;
    background-repeat: no-repeat;
}

The shortcut background property combines three or more properties into one, like this:

background: url(path/to/file.jpg) no-repeat top right;

Additional Resources

Create a full-page background with a stylesheet
LogRocket Blog 2023
Perfect Full Page Background Image
CSS Tricks 2022