Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

css
communitycreator

How to create responsive images with CSS

NDUKWE CHIDERA K.

One of the tricky tasks in web development is working with images. Developers often face various challenges that come with positioning, sizing, and making images responsive. In this shot, we will learn to make images responsive using CSS.

Responsive images

A responsive image can scale automatically with varying screen sizes. It will scale itself properly when displayed in browser windows of different sizes and in different devices.

A basic responsive image

The HTML file will include the img tag that holds our image of choice. This img tag should also have a class name. Our tag will look like the HTML code snippet below:

<img class = "standardImg" src = "your/preferred/image" alt ="responsive image">

Now that we have a basic image setup, we can style our image to be responsive. We will set width to 100%. This is relative to the image container, which can be body or a div.

img.standardImg {
 width: 100%;
 height: auto;
}

Our image is now responsive and will scale appropriately.

A responsive image with size limit

We can introduce a size limit by using the code snippet shown below:

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

In this case, we have set the original size of the image as the maximum possible size it can take.

We can specify max-width in terms of pixels. The code snippet below sets max-width to 600px.

img.standardImg {
 width: 100%;
 max-width:600px
 height: auto;
}

A working example

Let’s try what we have learned so far. Running the code below will render a responsive image in the output window.

Hit run! You'll see a responsive image in the output tab. Try resizing the browser size to see how the image scales.

Code explanation

  • In lines 3 and 16, we open and close the style tag, respectively. This allows us to apply styles in our HTML markup.
  • In lines 410, we style the div (with the class name holder) that keeps our image placed in the center of the display output.
  • In lines 1115, we style the image so that it becomes responsive. Try changing the code in these lines and see what happens.
  • In line 17, we close the head tag.
  • In lines 1822, we insert the body and the holder div. We also insert the image in the img tag, which we have made responsive.

If you are viewing this shot from a mobile device, comment out the img.standardImg styling in the HTML and observe the difference.

RELATED TAGS

css
communitycreator
RELATED COURSES

View all Courses

Keep Exploring