Open CheatSheet Back To List Next Tutorial

Working with Images (Video Tutorial)

Working with Images

Intro to Images

Build a Blog Site: This is the ninth part of the Build a Blog Site tutorial series.
The focus of this tutorial is on images.

Simulate Bootstrap: In this tutorial series we are mimicking Bootstrap classes, using the same Bootstrap class names, and applying the same or similar style but with less complex style rules.

Finished Code: The code is available on GitHub: github.com/LearnByCheating/learn-html-blog-site-example. There is a separate version with the finished code for each tutorial.

Live Server: If you are using VS Code as your text editor and have the Live Server extension installed, you can launch a local web server from the Editor to follow along.
  • Close any prior Live Server sessions by right-clicking in the editor, then select Stop Live Server.
  • If you are using the code from the GitHub link above, go to the .vscode/settings.json file and change the liveServer.settings.root value to the appropriate version: "liveServer.settings.root": "/v9-images" 
  • Right click in the html page and select "Open with Live Server". 

Written and Video tutorial: There are both a video and written version of each tutorial. For the HTML-CSS tutorial series the video and written versions have a different focus. The video tutorials are focused on the blog site project. The written tutorial is focused on the all the subtopics within the CheatSheet major topic.

CheatSheet: Part of the objective of this tutorial series is to become familiar with the CheatSheet so you can use it for quick reference going forward. As such, it is recommended that you review the CheatSheet category that aligns with this tutorial .


Images

You will almost certainly want to include images on your website. 

In this tutorial we will cover image file formats, the img, figure, and figcaption tags, image size, styling images, adding an image logo and favicon, Bootstrap classes and icons. And we will apply all these to our Blog Site project.


Understand image formats, img tags, and dimensions.

Image file formats

The most commonly used image formats on the web are jpeg, png, and svg.

Jpeg and Png:
 Jpeg and png files are bitmap images.
 
Bitmat images: (also called raster images) are made up of pixels in a grid.
Pixels are tiny squares, each with a specific color. Put together they form an image. They lose quality when resized larger. Photographs are bitmap images.

File compression: Web images are compressed to reduce the file size. Jpeg and Png have their own compression algorithm to remove data deemed unnecessary or redundant. This decreases file size but also image quality.

Png:
  • Png files generally have higher quality than jpeg files, but are larger in size. 
  • Png files allow for transparent backgrounds while jpeg files do not.
  • Use png format if the image is important like a logo or diagram. Or if your site only has a few images.
Jpeg:
  • Jpeg files can have jpg or jpeg file extensions.
  • Use jpeg when your site has many images with large png file size.

Svg:
Vector: Svg files are vector images. Vector image files contain mathematical formulas setting shapes, colors and placement that form the image. Vector files can be resized without quality loss.

Image placement:
Place the svg file in a folder with your other images, and put the image path in the img element src value: <img src="images/my-vector-image.svg">

While generally not recommended, you could place the svg file directly in your HTML as an svg element:  <svg ...>


The <img> element

Img is an empty element, meaning it does not have a closing tag.
Example: <img src="/path/pic.png" alt="Image description">

It has one required attribute and one highly recommended.

Src attribute: The source attribute is the URL or path to the image file. It can be an:
  • Absolute Path: Usually a URL to the image in another website: 
<img src="https://example.com/path/to/some-pic.png">
  • Relative Path: path to the image file in your project. Start the path with a slash to make it relative to the root of your project. Otherwise the path will be relative to the file the link is in.
<img src="/assets/images/some-pic.png">

Alt attribute: Provide a text description of the image. It is not required but very useful for two things: 
  • If the image fails to load for some reason, the alt text is displayed in its place.
  • For accessibility, it is read when the screen reader is turned on. 
    • Screen readers announce "image" when reading alt text, so don't include "image" in the description. 
    • Guideline: alternate text should be able to replace the image without altering the meaning of the page. But should not be construed as a caption or title since there are separate attributes and elements for that.
    • If the image is strictly for decorative purposes, set alt to empty text: <img alt=""> 

Default CSS
The img tag's display property is inline. That means it doesn't take up the whole row.
The height of the row becomes the height of the image.

Dimensions, Aspect Ratio, Resolution

Intrinsic dimensions:
All image files have an intrinsic width and height in pixels.
You can get the dimensions from the image itself.
On Mac:
  • In the Finder program, right-click the image and select Get Info. It will give you the image format, file size, and dimensions (width x height).
  • Open the image in the Preview app. From the Tools menu, select Adjust Size. That will show you the width and height dimensions, resolution, and lets you adjust the size. 

Aspect Ratio: The aspect Ratio is the ratio of width to height. If you change one of those dimensions, you need to change the other, using the aspect ratio to avoid distorting the image. 
The most common photo aspect ratios are 4:3, 3:2, 16:9.

Resolution: Number of pixels displayed per inch (PPI). For photos on the web 72 is generally sufficient.

Width and height: HTML attributes and CSS properties
An image will be displayed using its intrinsic dimensions. 
You can override this by setting the dimension as attributes of the img tag or in your CSS.

HTML Attributes:
You can set the width and height directly on the img tag using attributes:
<img src="images/my-pic.png" alt="" width="400" height="300">

Sometimes the HTML page will load before the images do. If you include width and height attributes, the page will create a placeholder for the image, 400px x 300px in the above example. When the image does load, there won't be a jump on the screen that pushes the other content down. 

CSS:
Alternatively you can set the dimensions with CSS. 
HTML document: <img src="images/my-pic.png" alt="" class="mypics"> 
Stylesheet: .mypics { width: 400px; height: 300px; }

CSS overrides attributes if there is a conflict. 

Unlike with the width and height attributes, with CSS you can use measurement units other than pixels, such as percentages or viewport width. And you can set minimum and maximum widths and heights.

Using percent or viewport width makes the images responsive to screen size. This prevents images from being wider than the screen, and will change the image size depending on the browser window width.

Percent: .mypics { width: 100%; height: auto; } 
  • Percent is relative to the parent element.
  • If you set width to a percent, set height to auto. That will automatically calculate the height based on the image aspect ratio.

Viewport Width: .mypics { width: vw100; height: auto; }  
  • Viewport width is like percent except it is relative to the viewport (browser window), not to the parent element.
  • vw100 sets width to 100% of the viewport. vw50 would set it to 50%. 
  • If you set width to a viewport Width, set height to auto. That will automatically calculate the height based on the image aspect ratio.



Image Classes

Bootstrap classes

As usual, we will be mimicking Bootstrap classes in our CSS. 

Bootstrap documentation on image styling is at: getbootstrap.com/docs > click Content: Images.


Blog Site Changes

Let's add and style images to the Blog Site app.

Image-related style rules:
stylesheets/mimic-bootstrap.css
/* IMAGE SPECIFIC CLASSES */
img, svg { vertical-align: middle; }
.img-fluid {
  max-width: 100%;
  height: auto;
}
.img-thumbnail {
  padding: 0.25rem;
  background-color: #fff;
  border: 1px solid #dee2e6;
  border-radius: 0.25rem;
  max-width: 100%;
  height: auto;
}
figure { margin: 0 0 1rem; }
.figure { display: inline-block; }
.figure-img {
  margin-bottom: 0.5rem;
  line-height: 1;
}
.figure-caption {
  font-size: .875em;
  color: #6c757d;
} /* CUSTOM IMAGE CLASS */ .img-75x75 { width: 75px; height: 75px; } /* OTHER CLASSES USED BY IMAGES */ .rounded { border-radius: .25rem!important;} .float-end { float: right!important; } .float-start { float: left!important; } .align-text-top { vertical-align: text-top!important; } .align-text-bottom { vertical-align: text-bottom!important; }


Round or Frame the image

To round the corners of the image, use the rounded class
.rounded { border-radius: .25rem!important;}

To put a frame around the image use the img-thumbnail class
.img-thumbnail {
  padding: 0.25rem;
  background-color: #fff;
  border: 1px solid #dee2e6;
  border-radius: 0.25rem;
  max-width: 100%;
  height: auto;
}
  • This adds .25rem (4px) padding to the image element.
  • Surrounding the padding is a 1px gray border around it with a .25rem radius to round the corners. 
  • Max-width 100% will not allow the image to be wider than the screen.
  • Height auto will reset the height of the image automatically using the image's aspect ratio. You need to pair this with the max-width 100%, otherwise the height will not shrink if the image width shrinks to fit the browser window.

We have a placeholder image called placeholder-x.png in the images folder.

The articles/article-template.html page has a section titled Image Examples where you can see the various image classes in action. Let's start with the rounded and img-thumbnail classes. 
articles/article-template.html
<img src="/images/placeholder-x.jpg" alt="Image Text" width="150" height="150" class="rounded img-fluid">
<img src="/images/placeholder-x.jpg" alt="Image Text" width="150" height="150" class="img-thumbnail img-fluid">


Image Caption

To add a caption to an image, wrap the image in figure tags, and put the caption in figcaption tags. 
articles/article-template.html
<figure class="figure">
  <img src="/images/placeholder-x.jpg" alt="Image Text" width="150" height="150" class="rounded figure-img img-fluid">
  <figcaption class="figure-caption">Image caption here.</figcaption>
</figure>

We added classes and style rules to adjust margin, line-height, font-size and color. The caption is gray and a smaller font size.
figure { margin: 0 0 1rem; }
.figure { display: inline-block; }
.figure-img {
  margin-bottom: 0.5rem;
  line-height: 1;
}
.figure-caption {
  font-size: .875em;
  color: #6c757d;
}


Make image responsive

If the browser window is narrower than the image width, then the image will go off the screen.
To avoid that happening, we'll add the class img-fluid.

Element with class:
<img src="/images/placeholder-x.jpg" alt="Image Text" width="150" height="150" class="rounded img-fluid">

CSS:
.img-fluid {
  max-width: 100%;
  height: auto;
}

Setting max-width to 100% shrinks the image to the width of the browser window if it is too wide.
Setting height to auto will automatically calculate the image height based on the aspect ratio.
Otherwise, if the image width shrinks to fit the window, the image height would stay the same and distort the image.


Horizontal Alignment

Images align to the left by default. 
To align the image to the center or right of the parent element:
Method 1) Set text alignment in the parent element.

articles/article-template.html
<div class="text-center">
  <img src="/images/placeholder-x.jpg" alt="Image Text" width="150" height="150" class="img-thumbnail img-fluid">
</div>

The CSS classes are:
.text-center { text-align: center; } 
.text-start { text-align: start; } /* Aligns text to the left */
.text-end { text-align: end; } /* Aligns text to the right */

Method 2) Alternatively, you can convert the image display from inline to block, then set the margin property to auto. Auto tells the browser to calculate the space available. Applying auto to the left will push the image all the way to the right. Applying auto to both the left and the right will push the image to the middle of the row. 

Align the image to the center:
<img src="/images/placeholder-x.jpg" alt="Image Text" width="150" height="150" class="d-block mx-auto">

Align the image to the right:
<img src="/images/placeholder-x.jpg" alt="Image Text" width="150" height="150" class="d-block ms-auto">

CSS Classes:
.d-block { display: block; }
.mx-auto { margin-left: auto!important; margin-right: auto!important; } .ms-auto { margin-left: auto!important; }

Float
You can float the image to the left or right. Then the elements that follow will wrap around it. Make sure to also add  margin. 

articles/article-template.html
<img src="/images/placeholder-x.jpg" alt="Image Text" width="75" height="75" class="float-end rounded ms-3">
This text will be to the left of the image separated by a margin of 16px.

CSS Classes:
.float-end { float: right!important; } /* Float image to the right */
.ms-3 { margin-left: 1rem!important; } /* Put margin to left of image */

.float-start { float: left!important; } /* Float image to the left */ .me-3 { margin-right: 1rem!important; } /* Put margin to right of image */


Align image with the Grid, and make it responsive with Media queries

Be warned that this section is somewhat complex.
  • On the index.html page we will use the grid to split the article summaries into two columns. The text will be in the left column and an image on the right.
    • Bootstrap uses the CSS Flexbox module for its grid while we are using the CSS Grid module for our grid, so some of the classes are different.
  • In addition, we will use media queries to make it responsive by making the images disappear when the browser window is less than 992px wide. 
  • The grid was covered in the earlier tutorial on Grid Layout. Media queries were covered in the earlier tutorial on Spacing. 

At the top of the page is the highlighted article:
index.html
<article class="text-white bg-dark rounded mb-5 row g-0 grid-67-33">
  <div class="col-md-8 p-4 p-lg-5">
    Put article title, author, summary, and link here...
  </div>
  <div class="col-md-4 p-4 p-lg-5 d-none d-md-block">
    <img src="/images/placeholder-x.jpg" alt="Image Text" class="rounded w-100 h-auto">
  </div>
</article>

  • row: The row class will split the article into a grid. 
  • The two child elements are split into two columns. The left column holding the article summary takes up 67% of the parent element's width, and the right column holding the image takes up 33%.
    • col-md-8 and col-md-4: Bootstrap creates the columns using the col-md-8 and col-md-4 classes and ignores the grid-67-33 class.
    • grid-67-33: Our own mimic-bootstrap stylesheet does that with the grid-67-33 class and ignores the col-md-8 and col-md-4 classes.
  • p-4: Sets padding to 1.5rem.
  • p-lg-5: Sets padding to 3rem if the browser window is 992px or wider. Note, this class must come after .p-4 in the stylesheet to take precedence since both are using the !important keyword.
  • d-none: This class sets the display property of the image to none, thus hiding the image.
  • d-md-block: This class changes the display property to block if the browser window is 768px or wider.
  • w-100 h-auto: The image width is 100% of the column. The height is automatically calculated based on width times the aspect ratio.

Our mimic-bootstrap class definitions for the above classes are as follows:
.row { display: grid; }
.d-none { display: none; } .p-4 { padding: 1.5rem!important; }
@media (min-width: 768px) {
  .grid-67-33 { grid-template-columns: 2fr 1fr; }
  .d-md-block { display: block; }
}
@media (min-width: 992px) {
  .grid-67-33-lg { grid-template-columns: 2fr 1fr; }
  .d-lg-block { display: block; }
  .p-lg-5 { padding: 3rem!important; }
} .w-100 { width: 100%; } .h-auto { height: auto; }

For the rest of the article summaries, the classes are mostly the same but there are some differences.
They are already inside a grid split into one column for articles and one for the table of contents.
Since Bootstrap is using Flexbox for its grid, it has a different class: flex-md-row.
But our mimic-bootstrap CSS uses the same row class as before.
index.html
<article class="card mb-3 row flex-md-row grid-67-33-lg g-0">
  <div class="col p-3">
    Put article title, author, summary, and link here...
  </div>
  <div class="col-auto p-3 d-none d-lg-block">
    <img src="/images/placeholder-x.jpg" alt="Image Text" width="200" height="200" class="rounded">
  </div>
</article>

Try it out in the Browser.
  • The images should be in columns to the right of the summary for articles 1-3. 
  • We didn't add an image with article 4 so it should just include the article summary text. 
  • Making the window narrower and wider should make the images disappear and reappear.

Vertical alignment - align logo image and site brand

If the image height is greater than the line height, the row will just expand to match the image's height.
By default, any text on that line will be aligned to the bottom.

Our CSS changes all img and svg element vertical-align to the middle.
img, svg { vertical-align: middle; }

We also added classes we can use to align the image with the text to the top or bottom of the font by adding the below classes to the img tag:
.align-text-top { vertical-align: text-top!important; }
.align-text-bottom { vertical-align: text-bottom!important; }

There is a logo image for our site in images/site_icon.png.

In the navbar, put the logo to the left of the Site Name.
index.html
<a class="navbar-brand" href="#">
  <img src="images/site_icon.png" alt="Site logo" width="25" height="25" class="align-text-top me-2">
  Site Name
</a>

  • The intrinsic size of this image is 128px by 128px. We want it smaller so we set the width and height properties to 25.
  • For the class, the me-2 will add margin-right of .5rem, or 8px. 
  • The image and text did not line up exactly right without adding the align-text-top class. That aligns the top of the image to the top of the parent element's font. In this case that worked. If you change the image height property to height="125" you can really see the impact of adding align-text-top, align-text-bottom, and removing it so it aligns to the middle. 


Favicon

We will use the site_icon.png file as our favicon. Favicon is the small image that appears in the browser tab. 

Just add a link in the head element to image and set the rel and type properties as below:
<link rel="icon" type="image/x-icon" href="/images/site_icon.png">

Refreshing the page should show the favicon on the browser tab. 

Bootstrap Icons

Bootstrap has a collection of icons in SVG format. 
You can see them at: icons.getbootstrap.com
At the bottom of that page, after all the icons, there are instructions for the various ways you can use them in your site. The CDN link is there as well.
Two ways to use them are:
  1. Download the specific icon svg files you want to use in your project, place them in your image folder, and in an img tag, put the image path in the svc attribute. This is like displaying any other image.
  2. Link to the Bootstrap Icons CDN and use the web font class in an empty i element. 

Let's use the second way.

Copy the Bootstrap Icons CDN from the web site, and paste it in the head element. 
<head>
  ...
  <link rel="stylesheet" href="URL GOES HERE">
</head>

We will use these images in our footer, in the anchor tags that link to the Social Media accounts. 
By putting the image inside the anchor tag, clicking the image also clicks the hyperlink.
<ul class="navbar-nav ms-auto">
  <li>
    <a class="nav-link" href="https://github.com/YOUR-USERNAME">
      <i class="bi-github" role="img" aria-label="GitHub"></i>
      Github
    </a>
  </li>
  <li>
    <a class="nav-link" href="https://twitter.com/YOUR-USERNAME">
      <i class="bi-twitter" role="img" aria-label="Twitter"></i>
      Twitter
    </a>
  </li>
  <li>
    <a class="nav-link" href="https://www.linkedin.com/YOUR-USERNAME">
      <i class="bi-linkedin" role="img" aria-label="LinkedIn"></i>
      LinkedIn
    </a>
  </li>
  <li>
    <a class="nav-link" href="https://www.facebook.com/YOUR-USERNAME">
      <i class="bi-facebook" role="img" aria-label="Facebook"></i>
      Facebook
    </a>
  </li>
</ul>


View the changes
Save the changes to the files, then view the result in the browser:
http://localhost:5500

To see if the display looks the same when using the Bootstrap CDN:
  • Comment out the local stylesheets/styles.css.
  • Uncomment the Bootstrap CDN link.
  • Refresh the page. It should look identical. 
  • Now switch it back. Comment out the Bootstrap CDN and uncomment the local stylesheet.
  • You may see a slight difference in the grid layout because of the different approaches we are using (CSS flexbox module vs CSS grid module).

Open CheatSheet Back To List Next Tutorial