< Go Back

7 day coding challenge

day four - images and backgrounds

Taught by Tina May

Creating an image element

Let’s start with the simplest option - creating an image in HTML:

<img src="https://www.instituteofcode.com/houdini.jpg">
<img src="https://www.instituteofcode.com/nala.jpg">

You’ll notice that images don’t have a closing tag, just an open tag with attributes inside. Usually, we have an open and close tag because we need to hold together the content in the middle which is a text. But when we’re displaying images, there is no text and we can tell the browser everything it needs to know just from the element itself. 

The src attribute links to the source of the image. Remember that if the image is hosted on the external website, you use its full URL. If it’s hosted on your own website, then you just link within the relevant folder without the full URL.

<img src="/images/houdini.jpg">
<img src="/images/nala.jpg">

If you’re working in Codepen you can’t upload your own images on the free plan so you need to use an image that’s already hosted. If you’re just playing around, you can save these two links of our puppies, or you can use any hosted image sites that provide placeholder images for temporary projects. Click here to see the list of these websites - they have everything from random images to kittens and Steven Seagal. 

Alternatively, you can use free stock images from websites that allow commercial usage like Unsplash.com. You can grab the image URL in two ways:

1) By copying the image address directly. For example:

<!-- Copy the Image Address directly -->

<img src="https://images.unsplash.com/photo-1544198365-f5d60b6d8190?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8bW91bnRhaW58ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60">

2) By using the Unsplash source app. This tool comes in really handy since you can easily generate a random image without being distracted by a long URL in your code. Here are the following options:

<!-- https://source.unsplash.com/imageID -->
<img src="https://source.unsplash.com/cqbLg3lZEpk">

<!-- https://source.unsplash.com/random -->
<img src="https://source.unsplash.com/random">

<!-- https://source.unsplash.com/random/ and simply add photo dimensions after the URL (ex: /800x600) -->
<img src="https://source.unsplash.com/random/800x600">

<!-- https://source.unsplash.com/featured/?keyword -->
<img src="https://source.unsplash.com/featured/?infant">

alt attribute

The alt attribute is what tells search engines and accessibility devices what the content of your image is, and it’s also what will show if your image fails to load on a slow internet connection.

<img src="/houdini.jpg" alt="an adorable black Bali dog">
<img src="/nala.jpg" alt="Nala the goldie jumping for confetti">

Styling images

Just like anchor links, images are inline elements by default - they naturally sit next to each other and flow in-line just until they run out of space and then dropping down.

You can either set a height or a width, but you wouldn’t want to set both otherwise the image will look ridiculously stretched out.

Alternatively - and this is what I use the most - we can instead set a max-height or a max-width. This says to the browser, let it take up whatever size it naturally be, but not bigger than the value we’ve specified.

And unlike height and width, if you set both max-height and max-width on the same selector, it won’t stretch or squeeze the image even though the value you set isn’t proportionate to the aspect ratio of the image. It will set the maximum value based on the longest side of both and the other one will follow naturally according to the aspect ratio.

These properties are really helpful for big images because if it’s too huge, it will break the page and you have to scroll in both directions to see it entirely. Images by default will display their natural size in pixels, so if you want to make them smaller you have to resize them before you upload or adjust them in the CSS.

Because of this, I always create a basic CSS that applies to every single image on my website which tells the browser that I never want my image to be bigger than the size of its container. I do this by setting a universal image style in my CSS with 100% of max-width.

img {
	max-width: 100%;
}

So if I haven’t given my image a specific styling property, it will automatically use a max-width of 100% and stay in its box. I always include this at the beginning of every project.

If your images have different shapes or sizes and they are sitting next to each other on a line, you can adjust their alignments with the vertical-align property. There are 3 common values that you can choose:

  • middle: align the elements to the middle;
  • top: align the elements to the top;
  • bottom: align the elements to the bottom.

Adding a background image

To create a background image we need to target that element in our CSS and apply the background to it. The background property styles the background of any element and container, such as a paragraph, link, section, or body. Let’s say we wanted to make our whole page have a background image, then we could apply it to the body element:

/*  This will set the background based an image stored in the main folder of your website. */

body {
	background-image: url('/background.jpg');
}

/*  This will set the background based an image hosted in external website. */

body {
	background-image: url('https://source.unsplash.com/PKEPAeMBOIU');
}

And if we do, we’re going to get something like this:

Depending on how big the image is and how big our browser window is, we might see a tiny zoomed-in corner of the image, or we might see the image repeated like tiles. Not exactly aesthetically pleasing. Luckily we have a few different properties that we can use to adjust the way our background image displays:

body {
	/* First we add the image */
	background-image: url('https://source.unsplash.com/PKEPAeMBOIU');

	/* then we set the size to cover the entire element */
	background-size: cover;

	/* then we tell the browser where to focus when the image crops */
	background-position: center;

	/* then we tell the browser not to repeat the image */
	background-repeat: no-repeat;

	/* and finally we tell the browser that the image should cover the entire browser window */
	min-height: 100vh;
}

The background-size property affects the size of the image in the background. The most common value for this property is cover (stretch the image to cover the entire box with the smallest possible size) and contain(squeeze the full image to fit inside the box and not cut off even if it means not covering the entire box and leaving negative space). Each property value you choose will always keep the aspect ratio of the image no matter what. And you want to start with an image that is big enough to cover all of the common devices your customers will be using, otherwise, your image could get pixelated.

The background-position affects part of the image that the browser tries to focus on. By default, background-position is set to the top left. Often we will want to override this with background-position: center; which will make the center of the image the focus point in the initial positioning of the background. If none of these values suit you exactly, background-position actually has many more property values to give you more flexibility. Click here to see the list.  

The background-repeat affects how the background image will be repeated. By default, it’s repeated both vertical and horizontally but generally, we don’t want any repeat so we put the value of no-repeat.

The min-height is a workaround on an HTML & CSS quirk that the body can only take up a certain size if there’s no content yet. If you add min-height: 100vh; the background image will cover 100% of the height of the browser window.

Tip: If you notice something doesn’t add up with how the styling calculates the size, make sure your CSS reset is in place:

* {
	padding: 0;
	margin: 0;
	box-sizing: border-box;
}

When to use HTML <img> or CSS background-image

A lot of time you’re going to be choosing whether to put your image directly into HTML or to create another element and apply a background image in the CSS. Here’s a general rule of thumb:

Use HTML <img>if you want to keep the images in their exact same aspect ratio, but first, make sure they’re cropped in a consistent size and shape before importing them into your website.

Use CSS background-image if you want to adapt the shape of the images to your design - let’s say if we have a gallery and we need every image to be the same size regardless of what the original is.

Creating a background image on an empty container

There’s a way you can create a background image on an empty container without text on the screen and that is by applying width and height to open up space in the container.

<div></div>
div {
	background-image: url(‘https://instituteofcode.com/houdini.jpg’);
	background-size: cover;
	background-position: center;
	width: 50%;
	height: 500px;
}

That’s it guys, give it a go, make yourself familiar with all of the stuff, and good luck!

activities

Your activity for this week is just to play with images and background images. You can try each one then delete it and create the next. 

  1. Apply a background image on the body. Set the background-size and background-position properties.
  2. Create 3x <img> elements and give each one a width of 25% and a margin of 1%
  3. Create 3x <div> elements and give each one a background image, background-size and background-position. Then give them either a height and width or padding to create space inside them.

As you get more advanced, you learn how to control the aspect ratio of each image in CSS, but for now just play around with these basic options and see what you come up with!

explore the 5-day coding challenge