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.
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.
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.
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;
}
Let’s try what we have learned so far. Running the code below will render a responsive image in the output window.
3
and 16
, we open and close the style tag, respectively. This allows us to apply styles in our HTML markup.4
–10
, we style the div (with the class name holder
) that keeps our image placed in the center of the display output.11
–15
, we style the image so that it becomes responsive. Try changing the code in these lines and see what happens.17
, we close the head tag.18
–22
, 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 theHTML
and observe the difference.
RELATED TAGS
CONTRIBUTOR
View all Courses