make an image smaller in css
Code snippet for how to make an image smaller in css with sample and detail explanation
Working with images in CSS is a vital skill for any web developer. This article will walk you through the step-by-step process of making an image smaller using CSS.
Sample Code
In CSS, you can decrease the size of an image using “height” and “width” properties. Let’s look at a code snippet showing how this works:
img {
width: 50%;
height: auto;
}
Here, the width of the image is set to 50% and the height is set to auto.
Code Explanation
Now, let us break down what the code does step by step:
-
img
: This is the selector which targets all the images (<img>
elements) in your HTML document. -
width: 50%;
: This attribute sets the width of these selected images. Typically, the width of an image is the distance from its left side to its right side. Here, it is set at 50%, this means the image will occupy 50% of the space of their containing element. You can adjust the percentage according to your needs. -
height: auto;
: This attribute refers to the height of the image; the distance from the top to bottom. By setting the height to auto, we’re asking the browser to maintain the aspect ratio of the image. This means that the browser will automatically adjust the height of the image while changing its width, preventing the image from distortion.
Please note that CSS works by overriding previous styles, so if the <img>
element already had a height or width attribute, this style would override it. Also note that these styles won’t resize the actual image file, they just change how the image is displayed in the browser.
So, by using CSS, you can efficiently control the size of your images without disturbing their original aspect ratio. It’s a quick, simple method that can vastly improve the look of your sites.