The author selected the Diversity in Tech Fund to receive a donation as part of the Write for DOnations program.
When styling images on a web page with CSS, there are many important ideas to keep in mind. By default, web browsers display images in a raw format at their default size. This can lead to images being larger than the rest of the content, or can introduce unexpected spacing problems for your page layout. This tutorial will lead you through examples of image styling for web pages, allowing you to make informed decisions about how images are displayed and altered to fit the context.
In this tutorial, you will create a web page consisting of content and three images. The first image will be loaded as an <img />
element on its own, the second will be wrapped in the <figure>
element with an appropriate <figcaption>
, and the third will use the <picture>
element to load different images at different screen sizes and use the object-fit
and object-position
properties to resize the image. You will also explore some of the fundamentals of responsive web design and ensure the accessibility of your images.
background-size
property, which you can learn more about in the How To Apply Background Styles to HTML Elements with CSS tutorial.index.html
that you can access from your text editor and web browser of choice. To get started, check out our How To Set Up Your HTML Project tutorial, and follow How To Use and Understand HTML Elements for instructions on how to view your HTML in your browser. If you’re new to HTML, try out the whole How To Build a Website with HTML series.In this section, you will set up the base HTML for all the visual styles you will write throughout the tutorial. You will also create your styles.css
file and add styles that set the layout of the content.
Start by opening index.html
in your text editor. Then, add the following HTML to the file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>City Night</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@300;400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles.css" />
</head>
<body>
</body>
</html>
There are several page aspects defined inside the <head>
element. The first <meta>
element specifies the character set to use for the text. This way, special characters like accent marks will render without special HTML codes. The second <meta>
element tells browsers (mobile browsers in particular) how to treat the width of the content; otherwise, the browser would simulate a 960px desktop width. Next, the <title>
element provides the browser with the title of the page. The <link>
elements load in the page styles. The first three load in the font, Inconsolata, from Google Fonts, and the last loads the styles you will write in this tutorial.
Next, the page will need content to style. You will use sample content from Cupcake Ipsum as filler text to use with the styles. Throughout the tutorial, additions to code from previous steps will be highlighted. Return to index.html
in your text editor and add the highlighted HTML from the following code block:
<!doctype html>
<html>
<head>
...
</head>
<body>
<main>
<h2>City Night</h2>
<p> Candy bonbon carrot cake jelly beans shortbread fruitcake. Donut lollipop shortbread soufflé cotton candy cupcake cake. Pastry bear claw powder shortbread gingerbread.</p>
<p>Caramels jelly-o marshmallow muffin macaroon bear claw candy canes gummies. Muffin shortbread sweet roll pastry marzipan pudding.</p>
<p>Danish gummies oat cake marzipan shortbread pudding chocolate cake. Donut biscuit danish chocolate cake marzipan. Bonbon cheesecake gingerbread sesame snaps brownie ice cream caramels halvah.</p>
</main>
</body>
</html>
The <main>
element contains the primary content of the page, with an <h2>
text heading of City Night
followed by three <p>
elements of content. As you work through the tutorial, you will add images to the page between the content.
Save your changes to index.html
, then create a file in the same directory called styles.css
. Open this file in your text editor. In your styles.css
file, add the CSS from the following code block:
body {
margin: 0;
font: 100% / 1.5 Inconsolata, monospace;
color: hsl(230, 100%, 95%);
background-color: hsl(230, 40%, 10%);
}
h2 {
font-size: 3.5rem;
font-weight: 300;
text-shadow: 0 0 1em hsla(320, 100%, 50%, 0.5),
0 0 0.125em hsla(320, 100%, 60%, 0.5),
-0.25em -0.125em 0.125em hsla(40, 100%, 60%, 0.125),
0.25em 0.125em 0.125em hsla(200, 100%, 60%, 0.25);
}
main {
margin: 2rem auto 4rem;
width: 90%;
max-width: 70rem;
}
p {
font-size: 1.25rem;
max-width: 75ch;
}
These styles add the visual aesthetic and layout to the page. The body
rule set adjusts the defaults to load the Inconsolata font, then changes the color to be light blue and the background color to a dark blue-purple. Next, the h2
header gets resized, uses a thinner font weight, and gains a unique effect with the use of the text-shadow
property. The main
element is set up to remain in the center of the page and stop growing in width once it reaches a size of 70rem
, which is approximately 1120px. Lastly,the p
selector sets the font-size
a bit larger to 1.25rem
and sets a separate max-width
to 75ch
, which is 75 characters at the current font-size.
Save your changes to styles.css
and then open your web browser. Select the File menu item, then select the Open option and load your index.html
file in the browser. The following image demonstrates how this HTML will render in the browser:
In this section, you created the initial HTML and CSS for this tutorial. You loaded a custom font on the page and created a distinctive headline by using the text-shadow
property. In the next section, you will add your first image to the page using the <img />
element, learn about its default browser styles, and set up the images on the page to be responsive.
<img />
ElementThere are several things to be aware of when working with images on the web. First, images are by default shown on a page pixel for pixel. This means that if an image is 2048 pixels tall and wide it will occupy that much space on the browser, often causing horizontal and vertical scrolling. Next, images are considered inline flow content, which means images are treated like text in a browser and can be placed inline. This can be beneficial when wrapping text around an image with a float
property, but otherwise it is best to separate images from text content to improve the final layout.
To start working with images in your web page, create a new directory called images
by running the following in your command prompt:
- mkdir images
Next, you will download a photo of a building with brightly colored doors by Luke Stackpoole. This image comes from the stock photography website Unsplash. Run the following curl
command to download the photo into the new images
directory:
- curl -sL https://assets.digitalocean.com/articles/68128/night-doors.jpg -o images/night-doors.jpg
Now that you have the image available on your computer to use, open index.html
in your text editor. After the first paragraph in the content, add an <img />
self-closing element with a src
attribute, as highlighted in the following code block:
...
<main>
<h2>City Nights</h2>
<p>Candy bonbon carrot cake jelly beans shortbread fruitcake. Donut lollipop shortbread soufflé cotton candy cupcake cake. Pastry bear claw powder shortbread gingerbread.</p>
<img src="images/night-doors.jpg" />
...
</main>
...
The src
attribute directs the browser to the image you downloaded from Unsplash.
A very important aspect of working with an image is to provide an alt
attribute with a description of the image. This will help various users of your website know the image content, especially those using a screen reader. It is helpful to provide details around the context of the image, especially as it pertains to the rest of the text content. If an image is purely for decorative purposes, an alt
attribute set to an empty string is acceptable, as otherwise a screen reader would read the file name.
The highlighted HTML in the following code block provides a alt
text description of this image:
...
<img src="images/night-doors.jpg" alt="Three floors of several brightly-colored doors with a person walking on the second floor" />
...
Save the addition of an image to index.html
, then open the file in your web browser. The image will load between the first and second paragraph. Resizing the browser will have no effect on the image, as shown in the following animation:
As mentioned at the beginning of the section, images are shown at their native size, regardless of screen size. In order to make this image fit more screen sizes, you will next give the image fluid dimensions. Fluid image media is a key tenet of responsive web design, a method of web development that emphasizes code that adjusts to the constraints of the screen or browser size.
In order to define fluid images, open styles.css
in your text editor. Create an img
element selector, then add a max-width
property with a value of 100%
, as highlighted in the following code block:
..
p {
font-size: 1.25rem;
max-width: 75ch;
}
img {
max-width: 100%;
}
The max-width
property tells images they can scale down to fit a space. It also allows the image to grow until it hits the native pixel size. This different from using the width
property set to 100%
, which would allow the image to grow beyond the native size if the container were larger than the image. Additionally, the default behavior of a browser is to scale an image proportionally, so no height
property is necessary.
Save your changes to styles.css
and then return to the browser and refresh index.html
. Resize the browser so that the images scales down and back up until it reaches its full pixel size. The following animation depicts how this resizing interaction is rendered in a browser:
In this section you worked with the <img />
tag and successfully loaded an image on the page. You used the alt
attribute on an image and applied a sufficient description of the image. Lastly, you tried out a way to resize all image to fit the space available. In the next section, you will use the <figure>
and <figcaption>
elements and change their default styling values.
<figure>
and <figcaption>
Often an image needs accompanying descriptive text to give the reader more context about the image, such as who is in the image or where the image is from. For this kind of situation, it is useful to place the <img />
inside a <figure>
element with a <figcaption>
element to hold the descriptive text. In this section, you will use these elements and adjust their default styles to overlay the text on a photo of a street in Tokyo by Jezael Melgoza.
First, run this curl
command in the following code block to download the image into the images
directory:
- curl -sL https://assets.digitalocean.com/articles/68128/tokyo-street.jpg -o images/tokyo-street.jpg
Next, open index.html
in your text editor. In between the second and third paragraphs, add a <figure>
element. Within the <figure>
, add a <img />
element with a src
attribute pointing to the image you just downloaded. Then, add alt
text that describes the contents of the photo. These updates are highlighted in the following code block:
...
<p>Caramels jelly-o marshmallow muffin macaroon bear claw candy canes gummies. Muffin shortbread sweet roll pastry marzipan pudding.</p>
<figure>
<img src="images/tokyo-street.jpg" alt="A motion blurred street with an in-focus taxi." />
</figure>
<p>Danish gummies oat cake marzipan shortbread pudding chocolate cake. Donut biscuit danish chocolate cake marzipan. Bonbon cheesecake gingerbread sesame snaps brownie ice cream caramels halvah.</p>
...
Save these updates, then return to your browser to load index.html
. The image is displayed between the second and third paragraphs, but due to default styling has some inset spacing applied, as shown in the following image:
The extra spacing of the <figure>
is applied with the margin
property on the left and right sides of the element. This is the default styling found on most browsers, which puts a 40px
margin on the left and right and a 1em
margin on the top and bottom.
To adjust this default style, return to styles.css
in your text editor. Create a new figure
element selector and inside add a margin
property set to 2rem 0
, as highlighted in the following code block:
...
img {
max-with: 100%;
}
figure {
margin: 2rem 0;
}
Setting the margin
to 2rem 0
will apply 2rem
spacing to the top and bottom of the figure
and remove the spacing on the sides. This gives the image more space between the text, but allows it to occupy more space.
Save your changes to styles.css
and return to your browser to refresh the page. The following image shows how the figure
spacing is now rendered:
Next, to add a caption for the image, return to index.html
in your text editor. Inside the <figure>
element and beneath the <img />
element, add a <figcaption>
tag. The highlighted HTML in the following code block demonstrates this setup with caption text:
...
<figure>
<img src="images/tokyo-street.jpg" alt="A motion blurred street with an in focus taxi." />
<figcaption>Taxi in Tokyo, Japan</figcaption>
</figure>
...
The contents of a caption are useful to provide further information about the image that is not clearly evident. This is unlike the alt
text, which describes in words the contents of the image. In this case, a useful caption is the location where the photo was taken.
Due to the HTML order, the <figcaption>
content will display below the image, but next you will style it so that it overlays the image with a dark gradient to help make the text legible.
Return to styles.css
in your text editor. In order to create an overlay, a position: relative
property value will need to be added to the figure
selector. Then, create a figcaption
element selector and add the following highlighted CSS:
...
figure {
margin: 2rem 0;
position: relative;
}
figcaption {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: 5rem 1rem 1rem;
background: linear-gradient(to top, hsla(230, 40%, 5%, 0.95), hsla(230, 40%, 5%, 0));
}
The figcaption
styles set the container to overlay the bottom of the image with the position
, bottom
, right
, and left
properties. Next, the padding
property is large on the top side with 5rem
to give ample space for the gradient to spread above the text content, and the left, right, and bottom sides have a smaller 1rem
spacing. Lastly, you create the gradient with the background
property’s linear-gradient()
value that transition’s a dark blue at 95% opacity up to the same color with 0% opacity. Together, this creates a shadowed edge at the bottom to contain the caption.
Save your changes to styles.css
and return to your browser to refresh the page. The gradient background of the <figcaption>
shows up at the bottom of the image, but it overshoots the image on the bottom and right sides. The following image shows a close-up view of the difference between the image and the gradient:
There are two different issues that cause this misalignment, which require two methods to adjust the styles and correct the issue.
The first deals with how <img />
elements are treated as inline text by default. This extra space at the bottom is the line-height
spacing that makes space between lines of text. There are two ways to adjust this, by either changing the line-height
of the <figure>
element or setting the <img>
to have a display
property set to block
.
The second issue is the difference in size between the image’s pixel-to-pixel dimensions and the max-width
of the <main>
element. Since the <figure>
is a block
element and the <figcaption>
is set to span from the left edge to the right edge, it grows to fill a space larger than the image. The first way to fix this issue is to change the <img />
to have a width
set to 100%
. By setting this width
the image will ignore the max-width: 100%
default and instead fill the whole space. Note that this approach can cause image distortion depending on the difference in size. The second strategy to fix this is to change the <figure>
to have a display
property set to inline-block
. This approach will cause the <figure>
element’s size to shrink to fit its contents.
Return to styles.css
in the text editor and add the display
approach for each issue. In the figure
selector, add a display
property set to a value of inline-block
. Then, create a figure img
descendant combinator selector with a display: block
, as highlighted in the following code block:
...
figure {
margin: 2rem 0;
position: relatve;
display: inline-block;
}
figure img {
display: block;
}
figcaption {
...
}
Save your changes to styles.css
and then refresh index.html
in the web browser. The <figure>
shrinks down to the natural size of the image and the image is no longer treated as text. The following image shows how this adjustment to the display
properties is rendered:
In this section, you used the <figure>
and <figcaption>
elements. You learned about the default styles of the <figure>
and <img />
elements and how to change them for a more controlled outcome. Lastly, you created a caption that overlays the image with contextual information about the photo. In the last section, you will work with styling the <picture>
element using the object-fit
and object-position
properties.
<picture>
When working with images across various screen sizes, there are times when the image isn’t the right size and needs to adapt to the layout. The <picture>
element exists to meet this need by defining different images to display at different screen sizes. The images can then be more tightly controlled with the object-fit
and object-position
properties, which set how an image scales between the specific sizes.
To begin working with the <picture>
element, you will need a series of different-sized images of the same source image. Use the following curl
command to download a zip archive of three images of the same aerial photo of Tokyo by Pawel Nolbert:
- curl -sL https://assets.digitalocean.com/articles/68128/picture.zip -o images/picture.zip
Once the zip file finishes downloading, extract the content to your image folder. Run the following command in your prompt to place the files in the images
directory:
- unzip images/picture.zip -d ./images
Now, open index.html
in your text editor. First, you will create a <div>
with a class
attribute of hero
between the opening <body>
and <main>
elements. Then add the remaining highlighted <picture>
elements from the following code block:
...
<body>
<div class="hero">
<picture>
<source srcset="images/tokyo-large.jpg" media="(min-width:70rem)" />
<source srcset="images/tokyo-medium.jpg" media="(min-width:40rem)" />
<img class="hero-image" src="images/tokyo-small.jpg" alt="Time-lapse exposure of a city at night." />
</picture>
</div>
<main>
...
The <picture>
element requires a specific structure consisting of as many <source />
elements as needed and one <img />
element as the last item inside. All the accessibility and styling of the <picture>
element comes from the <img />
element, which is why the <img />
has a class
and the <picture>
does not.
The <img />
is the default image that is used to start when there are no media query requirements. The <source />
elements define two things: the location of the image file with the srcset
attribute, and the screen size scenario with the media
attribute. The browser will then access and load the appropriate image for the stated screen size, swapping out the image if the size changes.
Save your changes to index.html
, then open the file in your web browser. The following animation depicts the browser swapping the images as the window grows in size:
As the screen size changes, the image size changes as well, causing the text below to be pushed further down the page. In order to create a consistent spacing between this hero image area and the content, height
properties can be set to maintain a consistent size.
Return to styles.css
in your text editor. At the bottom of the page, create a class selector for .hero
. In the selector block, add the highlighted CSS from the following code block:
...
.hero {
height: 80vh;
max-height: 40rem;
}
The height
value set to 80vh
means that the .hero
container will at the least take up 80% of the browser’s screen height. Then the max-height
property ensures that the .hero
will not grow larger than 40rem
, which is equivalent to 640 pixels tall.
Save your changes to styles.css
and refresh index.html
in the browser. As the following animation illustrates, the text now maintains a consistent position. Meanwhile the visual distance between the image and content adjusts to the point that the image slides behind the text:
This overlap of the text and the image is a result of the browser erring on the side of content remaining visible, even if it goes beyond its ancestor’s container. A quick fix for this would be to apply an overflow: hidden
on the .hero
element, but that does not address the extra space when the image is scaled down smaller. To create a solution for both issues, the object-fit
property can help by giving an image similar controls as a background image has with the background-size
property.
To begin working with object-fit
, return to styles.css
in your text editor. Since the <img />
element is the element that controls styling for a <picture>
element, create a class selector for .hero-image
and add the highlighted CSS from the following code block:
...
.hero {
height: 80vh;
max-height: 40rem;
}
.hero-image {
height: 100%;
width: 100%;
object-fit: cover;
}
In order to work with the object-fit
property, the image needs to be able to grow both vertically and horizontally. By setting the height
and width
properties to 100%
, you give the object-fit
property full control of resizing the image. Without the object-fit
property, the image would be squashed to fit the parent container. The cover
value allows the image to be edge to edge either vertically or horizontally, depending on the orientation of the container. The object-fit
property can accept the same values as the background-size
property, including contain
and dimension values.
Save this new addition to styles.css
and refresh index.html
in your web browser. The following animation illustrates how the object-fit
property allows the image to grow to fill the whole space of the .hero
container and be hidden when it crosses the edge of the container, just like a background image:
Lastly, there is the object-position
property. This works similarly to the background-position
property to allow an image to be anchored to a specific area.
Return to styles.css
in your text editor and add an object-position
property to the .hero-image
selector. Set the value of the property to bottom right
, which will anchor the image to the bottom right area as it resizes. The highlighted CSS in the following code block demonstrate how this is written:
...
.hero-image {
height: 100%;
width: 100%;
object-fit: cover;
object-position: bottom right;
}
Save this change to styles.css
, then return to your browser and refresh index.html
.
This time as the browser width changes and the image scales, the scaling stems from the center of the container, as shown in the following animation:
This section introduced you to the <picture>
media elements, the object-fit
property, and the object-position
property. You used this combination of elements and properties to create a resizing and adjusting large image at the top of the page.
With the techniques you practiced throughout this tutorial, you are now prepared to write styles that will format images to fit your design and layout. You created responsive images by setting a global max-width: 100%
to all <img />
elements on the page. Next, you formatted an image caption to overlay the image and grow and shrink with the image. Then, you used the <picture>
element along with the object-fit
and object-position
properties to swap and scale images to best fit the screen size. Using these strategies will help you solve more complex situations involving images and page layout.
If you would like to read more CSS tutorials, try out the other tutorials in the How To Style HTML with CSS series.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Cascading Style Sheets (CSS) is the styling language of the web, and is used to design and control the visual representation of Hypertext Markup Language (HTML) on a web page. With CSS, you can manage everything from font to layout to animations on your web page. This series will lead the reader through CSS exercises that demonstrate the building blocks of the language and the fundamental design principles needed to make a user-friendly web site.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!