Images on the web
Back in time, somewhere in between 1992 and 1993, users of the then-static web began to seek features to be able to include images in HTML documents. There are many formatting capabilities in HTML by then, however, still it was void of any standard image rendering features.
Soon, the Moscaic browser led the way with the first ever element in HTML to render images — <img>
. Generally, Marc Andreessen is considered to be the person behind its inception (later founder of Netscape).
Now, web developers were finally able to render images on the web. From that day to today, the <img>
element has rightfully stood the test of time and not just that, but has become an integral part of all but the simplest of websites.
Let's explore what it has to offer us...
The <img>
element
The <img>
element, as the name suggests, is used to represent an image in HTML.
<img>
element represets an image in an HTML document.It is a void element, i.e. it doesn't have an ending tag. And honestly, there isn't even a need for an ending tag — what would've gone inside <img>
and </img>
tags if the element had been a container element?
Keep in mind that <img>
isn't strictly the only way to add images to a webpage; we can use <canvas>
, <svg>
(only for SVG images), and even some CSS to do so (using background images).
But using <img>
for doing so is the recommended approach, for it leads to better accessibility and is also a great thing for SEO, complementing the written text on our webpages with visual media that can independently be indexed on search engines.
While there are numerous attributes that can be set on <img>
elements, the most important ones are src
and alt
.
Image source and the src
attribute
It's not difficult to reason about the purpose of the src
attribute of an <img>
element. <img>
's purpose is to render an image, so before it can possibly render it, it needs the image's data from somewhere, isn't that so?
This 'somewhere' is essentially referred to as the image's source, or even as its location.
The source of an image is specified in the src
attribute of the <img>
element.
Typically, the source is a URL pointing to an image file. In this case, the same rules apply to getting to the image resource as from another resource on the web as we learnt in the chapter, HTML URIs.
For example, say we have a PNG image file named cat.png residing at the root of the website https://www.example.com. In this case, the source/location of the image would be as follows: https://www.example.com/cat.png.
Similary, if we have a JPG file named greeting.jpg in the same directory as our HTML document, its source could simply be a relative URL such as ./greeting.jpg (or even just greeting.jpg).
Simple.
Let's consider a quick example illustrating this.
Create a new HTML document with the necessary boilerplate markup in it. Next up, in the same directory as this HTML document, add in any image file of your choice.
We'll go with the following image, taken from Pexels, named html.jpg:
To render this image in the HTML document, we'll write the following <img>
element:
<img src="html.jpg">
And voila! There we have our image.
If the image was in the parent directory, we'd lay out src
as follows, starting with the ..
symbol (representing the parent directory):
<img src="../html.jpg">
On the same lines, if the image was on some website, let's say www.example.com, under the path /images
, src
would be an absolute URL:
<img src="https://www.example.com/images/html.jpg">
These aren't new concepts, so to speak; they're precisely what we learnt about URLs in HTML back in the HTML URIs chapter.
With src
explored, let's now understand the second most important <img>
attribute — alt
.
Alternative text via alt
In the example above, we referred to an image in the <img>
element, html.jpg to be specific, and the image got loaded successfully. Well and good.
Unfortunately, the case isn't always this simple. Sometimes, images might not load or if they do, they might not be rendered, perhaps because of some corruption in the image's data.
Failures in loading images
It's not always the case that the <img>
element ends with success; sometimes, there are failures encountered in the process.
Some reasons for failure are as follows:
- The source of the image is a non-existent URL.
- The image resides on another website and thus has be fetched across the network, however, the computer doesn't have internet access and thus the image file can't be requested.
- The image file is unsupported (for e.g. rendering an HTML document as an image).
- The image's data is malformed.
Either way, the end result is that the <img>
element doesn't have an image to display.
In this case, browsers resort to displaying an alternate text in place of the actual image to indicate to the user what the image was meant to showcase.
But it's not always about failure to render an image properly that we seek the need of alternate text.
Alternate text also helps users with visual disabilities to parse image content and understand what it's meant to represent in an HTML document. Screen readers read the alternate text of an <img>
element when they encounter one.
alt
attribute.For instance, going with the example shown above, we know that the image makes up the word 'HTML' using some letter blocks. Likewise, some possible options for the alternate text could be:
- The word 'HTML' constructed using letter blocks.
- Photo depicting 'HTML' using letter blocks.
- The word 'HTML' photographed.
Let's apply one of these to our <img>
element example:
<img src="html.jpg" alt="The word 'HTML' constructed using letter blocks.">
As can be seen, the value of alt
is simply the text that we think conveys the purpose of an image in the most concise way.
alt
, however it's recommended to keep it short and concise.Visually, this won't produce any effect whatsoever; alt
is mainly meant for accessibility purposes and for showcasing some text when an image fails to render properly.
Hmm. What if we deliberately get the image above to fail and see how alt
gets displayed?
Seems a good suggestion, so let's act on it right away:
<img src="no-such-image.jpg" alt="The word 'HTML' constructed using letter blocks.">
Here we've changed our image's src
to a non-existent path. It's clear that the image would fail to load, and that's exactly what we want, for we are interested in the outcome of this.
Time to see what gets rendered:
As can be seen, the browser displays the alt
text right where the <img>
was meant to render. This is preceded by a small icon that depicts an image to make it clear that the text is part of an image (specifically, its alt
text).
While we can omit the alt
attribute, it's definitely NOT a good practice to. Essentially, all <img>
elements must have an alt
attribute set on them.
This is for the sake of accessibility (which is paramount for us web developers to address) and for the sake of conformation with the HTML standard.
Specifying image dimensions
In the example above, the image we used was naturally 640 pixels wide and 426 pixels tall, concisely written as having the dimensions 640 x 426.
By default, when we render an image using <img>
, its natural dimensions are used in displaying it.
For example, if an image is 3000 pixels wide (and the browser's viewport is just, let's say, 1000 pixels wide), the image would overflow out of the viewport when rendered as is using <img>
.
However, using the width
and height
attributes, we can modify this behavior.
As per the names, width
is used to specify the width of the underlying <img>
while height
goes with its height. Both of these attributes, if given, are assigned numbers representing lengths in units of pixels (px).
If only one attribute is specified (width
or height
) the other one is automatically adjusted based on the aspect ratio of the image.
Let's consider two examples. First, we'll assign our <img>
element a given width
but not a height
, and then a height
but not a width
.
Following is the first case (omitting the alt
attribute for brevity):
<img src="html.jpg" width="300">
And following is the second one:
<img src="html.jpg" height="400">
If we apply both width
and height
, we must make sure to do so while respecting the image's aspect ratio, otherwise the image will get distorted.
Believe it, the last thing you ever want on a webpage is distorted images.
Let's illustrate what we mean by being distorted. Recall the natural dimensions of the html.jpg image we've been using thus far in this chapter: 640 (width) x 426 (height).
If we apply a custom width of 300px, based on this aspect ratio, the height must be almost 200px (= 426 / 640 * 300). This is applied as follows:
We get our image rendered with perfect form, no distortions.
<img src="html.jpg" width="300" height="200">
Now, let's take the height way up to 600px and see the result:
<img src="html.jpg" width="300" height="600">
Awful! Seriously, awful!
Apart from being distorted, the image has also lost its quality as we are rendering it beyond its natural size.
To boil it down, always set width
and height
carefully!
Never disrespect the aspect ratio of an image or up-scale it (down-scaling is OK but still the best results are obtained by sticking to the natural dimensions), for doing so will only lead to poor image rendering.
But there's one problem with width
and height
, a particularly concerning one.
That is, width
and height
specify the absolute dimensions of an image, giving no concern to the screen size where the image is going to render on. An image won't resize itself to fit its container when these attributes are set.
For instance, a width="500"
specification on an <img>
element will be perfect for a desktop device but for a mobile device, with a screen width of 420 pixels, not quite so.
We need a better approach. We need responsive images.
Responsive images
Consider the following display of our image file on a viewport of 300 pixels (recall that the image's natural width is 640px):
Notice the scrollbar at the bottom. This is bad in today's world of responsive design. OK, let's be fair, it's extremely bad.
A responsive website would look perfect on a desktop, perfect on a tablet, and perfect on a mobile — simply perfect on any device.
An unresponsive website on the other hand might look perfect on a desktop but extremely poor on a mobile device, rendering in the exact same way as it did on the desktop, with scrollbars here and there. An unresponsive website renders the same way on every single device, effectively being agnostic of it.
There are multiple aspects to creating responsive websites. One obvious part is to have responsive images.
So what exactly are responsive images?
Well, in simple words,
While setting width
and height
attributes on <img>
elements is good because in that way the browser right away knows how much space to alot to each image in the document's flow, they lead to unresponsive images.
If we need responsive images, we ought to use CSS's width
and height
properties alongside its idea of relative dimensions.
We'll try to keep the discussion concise for now since there is a lot to explore in the arena of responsive images.
In order to make an image fit nicely within its available space, we can set the CSS width
property and assign it the value 100%
. This will get the image's width to be 100% of the width of its parent. As we resize the browser, the CSS engine will remember to rescale the image to fit into its parent.
This is demonstrated as follows:
<img src="html.jpg" style="width: 100%">
Notice how the image has been condensed down to fit into the document and how there is no horizontal scrollbar on the webpage.
This is reminiscent of the fact that our image has become responsive. Great job!
Owing to the way how images are rendered by default and the way the examples in this chapter have been set up, setting the CSS property height: 100%
on the images won't work. And that's why we don't demonstrate it here.
Using images ethically
Before ending this chapter, there's a crucial point to address, one that perhaps many novice web users are not aware of which they should rather be, sooner than they'd want to.
Have you ever copy/pasted any image online and used it in your project?
If yes, then this is the high time to get you to realize an important aspect of asset ownership.
Respect copyrights
Images produced by an individual/brand — whether diagrams, illustrations, photos, or any artwork — are all belongings of the individual/brand.
They are a property of the concerned entity and protected by copyright laws.
In that sense, because using someone else's property without his/her notice is considered illegal, the same applies to images (and any other media) on the web. That is, using images owned by an entity (individual or brand) without its permission is considered illegal, better known as copyright infringement.
Copyright infringement can lead to the owning party filing legal cases against an offender and thereafter, asking for reimbursement.
So how do we keep ourselves from infringing anyone's copyrights when using images in our HTML documents?
Well, first and foremost, stop copying images from Google.
Using Google Images for getting images to use on your website is the easiest way to copyright infringement. It's OK to use images from Google for the sake of reference but embedding them onto your website is another story.
A free image doesn't mean it's free to use!
Remember that an image available to us for free (for e.g. via Google Images) doesn't necessarily mean that it's free to use it in any way we like to.
Always consult whether an image is really allowed to be used by its owner. Usually, this can be inspected by visiting the website containing the original image.
If there is a contact link on the website, use it to contact the owning entity and ask for permission for using its images. Other times, the website might clearly label the licensing terms of the image in which case just read through them to determine whether you're allowed to use the image or not.
Secondly, try to find images that are copyright-free, i.e. ones that don't have copyrights associated with them and can, likewise, be used in any (valid) way. This is sometimes also referred to as images in the public domain.
A great place to search for and download absolutely-free-to-use images is Pexels.
Thirdly, consider purchasing the license of an image if it's a stock photo.
A popular concept in this respect is that of royalty-free images. Leaving aside the legal jargon, this license allows us to use an image in any (valid) way we like to, without having to pay the creator on a per usage basis — it's a one-time fee.
Keep in mind, though, that royalty-free doesn't always mean 'free'.
Lastly, create your own images to let go off this hastle completely and not worry about any sort of copyright problems.
This last option, needless to say, is expensive given that you have to find professional photographers and illustrators to make images for you. And this is why some people turn to stock images or copyright-free images in order to reduce their expenses on imagery.
But remember: Since stock and copyright-free images are potentially used by many people, using them might not be able to establish a unique visual identity for you or your brand. So use with care.
Very few online resources teaching HTML images talk about copyright issues, and thus we feel this to be the high time to incorporate this paramount knowledge into our course because it's not only important but a part and parcel of your development career — you don't want to be infringing other people's copyrights, right?
Refrain from hotlinking
Related to the idea of copyright infringement online when using an image is that of hotlinking.
In simplest words, hotlinking is linking to some entity's images (which might be a case of infringing its copyrights) from that entity's own servers.
Hotlinking means that we don't download an image on our own server and then use it from our very own resources; it rather means to let go off all this and simply link to the resource on the external website.
Hotlinking is even more unethical than using someone's images without that person's consent. Why? Well because now you're not just using someone else's work but using their server's resources as well.
Besides these unethical reasons, hotlinking has some technical disadvantages as well.
By linking to another website directly for the image, you're exposing your own website's visitors to the backend of that image's website. It might:
- store the IP addresses of users on its end and then pass them on to a third-party;
- remove the image on its end, leading to your visitors seeing broken images;
- return back strange images in response to your hotlinking, potentially putting your site's visitors away (for e.g. returning a warning sign instead of a cute cat picture).
So, all in all, hotlinking images is highly unethical and something which diverts control of an image's content from our end to the end of the entity owning that image on another website.
Always serve images from the server where your website resides or, in case you have separate servers for static assets, make sure that you own those servers (in a way that you have control over what's delivered).
Right now, you obviously don't need to worry about servers, static assets, and all that stuff but once you do get to learn about HTTP and web servers, this discussion on images will be worth the time.