OneBite.Dev - Coding blog in a bite size

resize image css

Code snippet for how to resize image css with sample and detail explanation

When creating webpages, it’s crucial to ensure that our content, particularly images, are visually appealing and do not disrupt the overall layout of the page. One technique developers use to accomplish this is by resizing images using CSS.

Code snippet: Resizing an Image using CSS

Let’s have a look at the basic CSS code which enables us to resize images.

img {
   width: 100px;
   height: 100px;
}

With the above code snippet, any image placed within the HTML structure of the web page would be resized to a width and height of 100 pixels.

Code Explanation for Resizing an Image using CSS

This CSS rule targets ‘img’ elements throughout the document. ‘img’ is the HTML tag used to display an image on a webpage. The curly braces {} that follow contain the rules to be applied to those elements.

In the code snippet, we have set properties ‘width’ and ‘height’ each to ‘100px’. This means, all images targeted will be resized to a width and height of 100 pixels. Regardless of their original size, these images will now conform to the specified measurements.

It’s important to note that the values of ‘width’ and ‘height’ can be adjusted based on the design needs of your webpage. You can also use percentages instead of pixel values, which can be particularly helpful in creating a responsive design. For example:

img {
    width: 50%;
    height: auto;
}

In the above example, the width of the image will be 50% of its parent container, and the height is set to ‘auto’ to keep the aspect ratio of the image intact, preventing distortion.

And there you have it, a simple method to resize image using CSS. Practice a few variations of this, and you’ll soon find the right balance for your web design needs.

css