Introduction
There are two ways of adding images to the page:
- You can add an image to the HTML document using the
<img>
tag - Or you can add the image using the
background-image
CSS property.
Choosing which option is suitable for the image you want to add is essentially one of semantics and the practicalities of your chosen layout.
In general, if the image you’re looking to add is there to make the site look good, then adding it using CSS is best. If the image is there for content reasons and it would be useful for someone using assistive technologies or a search engine to know that this image is in the content of the page, then use the <img>
tag.
The two most common formats you’ll use for images are PNG, which is great for icons and logos as you can keep space in the image, and JPG, which offers excellent compression for pictures.
Images in HTML
We add images to HTML using the <img>
tag like so:
<img src="images/logo.png" alt="Logo of MyWebsite.com" class="logo" width="500" height="600" />
- The first attribute you will see is the
src
attribute which tells the HTML where the file is located. You should use a relative file path if the image is located in your project folder and not on a different server. - The second is the
alt
attribute which sets the alternative text for the image. Thealt
attribute is what assistive technologies and search engines use to know what the image is about. If you are adding an image to the HTML, it needs to have alt text.
Styling HTML images
You might also note that we’re not setting widths or heights in the HTML. All styling of the image should be handled in CSS. You do have specific HTML attributes called height
and width
, but the use of these attributes is mostly deprecated.
.logo {
max-width: 200px;
}
In the CSS above, we are using max-width
rather than a fixed width
. The reason for that is to avoid horizontal scrollbars. The browser will add a scrollbar when an element gets larger than the viewport. You want to avoid unintentional horizontal scrollbars. Setting the max-width
property ensures that the image won’t get larger than a certain size. However, as soon as other elements bump into it, the logo will reduce in size to allow space for the other elements rather than forcing a horizontal scrollbar to appear.
Another popular way of managing image sizes is using the percentage unit. This is especially useful if the image is inside a containing element such as <div>
or <section>
and you are already controlling the size of this element.
.product {
width: 300px;
}
.product-image {
max-width: 100%;
}
Please note that editing both the height and width of an image will result in an incorrect aspect ratio, making the image look stretched or squashed. As a rule, always leave either height
or width
as auto
in order to preserve this ratio. Generally speaking, the height should be auto rather than the width:
img {
height: auto;
width: 100%;
max-width: 100%;
}
Srcset
Although we can use the src
attribute to set the image location, this only gives us the opportunity to set one image for all users. This can be troublesome when handling mobile users who may not have such a strong connection and do not need to download a high resolution image. In the past, complex custom solutions were used to provide differently sized versions of the same image to different viewports. Today, we have access to the srcset
attribute, which allows us to set multiple images for different viewports.
<img
srcset="
images-icons/banner-1200w.jpeg 1200w,
images-icons/banner-1000w.jpeg 1000w,
images-icons/banner-800w.jpeg 800w,
images-icons/banner-400w.jpeg 400w
"
sizes="(max-width: 400px) 400px,
(max-width: 800px) 800px,
(max-width: 1000px) 1000px,
1200px"
src="images-icons/banner.jpeg"
alt="A calm sea with rocky shoreline and distant misty hills under a clear sky."
/>
By defining multiple sizes and image files, we effectively create a media query inside of our image tag. This leads to better performance for mobile users without degradation on large screens.
Object-fit
The object-fit
property defines how an image is resized. If you’re setting both a height and width on an image, it can sometimes get distorted. To fix this, you can use object-fit: cover
to crop the image on the page. You can also control what part of the image gets cropped using object-position
.
.product-image {
object-fit: cover;
object-position: bottom;
}
Other values for object-fit
include fill
, contain
, scale-down
, and none
.
This is particularly useful for creating banner decorations:
.banner {
position: relative;
height: 10rem;
}
.banner-image {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
margin: 0;
}
.banner-content {
position: absolute;
inset: 0;
padding: 1rem;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
<div class="banner">
<img src="images-icons/banner.jpeg" alt="Banner" class="banner-image" />
<div class="banner-content">
<h1>My Banner</h1>
</div>
</div>
Border-radius
If you wanted to create rounded edges on your image, for example, for a profile picture, you would use the border-radius
property.
border-radius
can be used on other elements as well.
You can decide how rounded you want the corners and which corners you want to be rounded.
.profile-pic {
border-radius: 50%;
}
The above code adds a 50% border-radius to each corner of the image, making it a perfect circle. If you only define one value for the border-radius
property, it will apply to all corners, but you can apply a unique radius to each corner by setting the value for all four, like so:
.product-image {
border-radius: 20px 50px 30px 10px;
}
The values are applied clockwise, so the first value applies to the top-left corner, then the top-right, then the bottom-right, and then the bottom-left.
Let’s apply these to the banner above:
.banner.rounded {
border-radius: 2rem;
border-bottom-right-radius: 0;
overflow: hidden;
}
Images in CSS
We need to use the background-image property to add an image using CSS.
header {
background-image: url('../images/header.jpg');
background-size: cover;
background-repeat: no-repeat;
}
Above, we can see a background-image
property is applied to the header. We use the url()
value to give a file path to the image we want to load. Again, it’s important to use the correct file path and ensure the image is loading correctly. The URL should be relative to the CSS file in which it is written.
Background-size
We have also set the background-size
property. In this case, we’ve set it to cover, which means that the image will scale as large as possible without stretching the image, and it will crop the image if there is no space either horizontally or vertically.
Other values for background-size
include contain
, which, like cover
, scales with the element to which it is applied, but it won’t crop. You can also set a pixel length or a percentage.
Background-repeat
By default, the browser will repeat your background image if there is available space to do so. A repeated background might be fine for a texture or pattern, but generally, it’s not ideal, so setting background-repeat: no-repeat
ensures the background appears only once. Other values for background-repeat
include: repeat
, repeat-x
, repeat-y,
space
, and round
.
Check out this site for some tiling/texture inspiration: Subtle Patterns.
Background-color
While on the topic of backgrounds, it’s worth mentioning the background-color
property, which allows you to set the colour of an element. On the other hand, the text colour inside the element is set by the color
property.
Background
There is a shorthand for managing backgrounds. Instead of writing each property on its own line, we can write it in one line like so:
header {
background: cover no-repeat url('../images/header.jpg');
}
Font Awesome
One of the most popular sets of icons online is the Font Awesome library. Here you are able to add icons directly into your HTML using short code snippets provided to you by Font Awesome.
Steps:
- Go to the Font Awesome website.
- Register for an account. Creating an account will allow you to get access to their CDN (Content Delivery Network), where you will be able to load icons from their network.
- When you’ve signed up, you’ll be given a script tag which you can add to the head of your HTML document.
- Once you’ve added the script tag to each HTML page on which you want icons, you can start adding the icons to the HTML.
There is a huge library of icons from which to choose. Once you’ve chosen your icons, you can add them like so:
<i class="fas fa-arrow-circle-right"></i>
Activities
WATCHThis tutorial video on using and adding images to the page. (6m 10s)
Lesson Task
Brief
There are practice questions in the master branch of this repo.
Attempt the answers before checking them against the answers in the answers branch of the repo.