OneBite.Dev - Coding blog in a bite size

resize images in css

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

CSS often acts as a powerful tool that can be used in enhancing our web designs. There is always the possibility of making our images into the desired sizes. The following article gives a thorough discussion on how to resize images in CSS.

Code snippet to resize images in CSS

To resize an image with CSS, you can use the following code snippet.

html{
  width: 100%;
  height: 100%;
}

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

In this code example, we are setting the image’s width and height to 50% of the width and height of the parent block (in this case, the html block).

Code Explanation for resizing images in CSS

To understand how the code works, let’s break it down.

  1. The html attribute: This attribute simply selects the HTML document. width: 100%; and height: 100%; set the width and height of the page to the full browser window.

  2. The img attribute: This one refers to the image element in the HTML document. When you write width: 50%; and height: 50%;, it sets the width and height of the image to be 50% of the parent block.

The percentage value allows for the image to be responsive to the parent block changes. This means if the window size changes, so does the size of the image.

However, it is important to note that using width: 50%; and height: 50%; could distort the image if the original aspect ratio is not a square. To keep the aspect ratio of the image, you could just set the width or height, and the other will auto-adjust to maintain the image aspect ratio.

For example:

img {
  width: 50%;
}

By summoning the command above, the browser will retain the natural aspect ratio of the image while applying the width reduction.

We hope you’ve got a clear understanding of how resizing an image in CSS works. Enjoy the journey in transforming your webpage’s looks!

css