Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resize images using % in css

I am trying to create a liquid web layout using % for as many things as i can. I have hit a bump when resizing images.

both:

<img src="source" style="width: 20%; height: 20%;"/>

and

.wall_picture_block img{
width: 20%; 
height: 20%;
}

don't work properly with the height attribte. They resize the image width to 20% of the container but the height stays relative to the image size.(im trying to make squares)

like image 438
slexAtrukov Avatar asked Sep 26 '10 10:09

slexAtrukov


People also ask

How do you resize an image proportionally in CSS?

Resize images with the CSS width and height properties Another way of resizing images is using the CSS width and height properties. Set the width property to a percentage value and the height to "auto". The image is going to be responsive (it will scale up and down).

How do you resize an object in CSS?

The scale() CSS function defines a transformation that resizes an element on the 2D plane. Because the amount of scaling is defined by a vector, it can resize the horizontal and vertical dimensions at different scales. Its result is a <transform-function> data type.

How do I resize an image without losing quality CSS?

Use object fit property in your css, and give a fixed width and height to your image tag or respective class so that every image will have same width and height, Now Your Image won't be distorted. Save this answer.


2 Answers

The percentages in height and width attributes of an image works with the container it is contained in. So to achieve the fluid effect just trying putting in a container around the img and give image height and width: 100%. and now you should be changing the height and width of the container in percentages. Here's an example

<div style="width: 500px; height: 100px;">
   <img src="your-image-link-here" style="height: 100%; width: 100%;">
</div>

With this your image will achieve a height and width of 500 * 100.

UPDATE

<div id="wrapper" style="border: 1px solid red; width: 900px; height: 400px;">
  <div id="imgcontainer" style="width: 100%; height: 50%;">
     <img src="ur-img" style="height: 100%; width: 100%;">
  </div>
</div>

Example with a wrapper and the container with the percentages.

like image 144
offhell Avatar answered Nov 03 '22 13:11

offhell


You should crop the image. Once you use a % for width or height, I think the browser tries to preserve the aspect ratio, regardless of the value for the other dimension.

like image 35
letronje Avatar answered Nov 03 '22 13:11

letronje