Reputation: 2587
I am loading a while bunch of photos onto my page and they are all different sizes. I need to bring them all down to the same size* (which is: x200px by y400px) _while maintaining aspect ratio.
How do I do this in pure CSS?
Upvotes: 1
Views: 129
Reputation: 707
The following CSS class will restrict them to the sizes you specified. diffferent aspect ratios may have smaller height or width but the aspect ratio is maintained
.yourimage{
width:200px;
height:400px;
background-image: url("yourimage.png");
background-size: contain;
background-repeat:no-repeat;
background-position: center ;
}
here is a fiddle with example http://jsfiddle.net/LgZtD/
Upvotes: 6
Reputation: 2168
I think this is what you are looking for:
img {
height: auto;
width: auto;
max-height: 400px;
max-width: 200px;
}
Upvotes: 1
Reputation: 371
CSS cannot change the sizes of your images, that's not what it is for. You will lose the aspect ratio if you insert the images into img tags with width:200px and height:40ppx.
What you can do though is use CSS to show a 200px x 400px element with the image as a background, and then use the background-size property to have the image cover the 200px x 400px space. CSS will find the most efficient way to cover that area without changing the size of the image
.image {
width: 200px;
height: 400px;
background-image: url(/url/to/image);
background-size: cover; //This will cover the area of the image
background-position: center center; //Have the image centered
}
http://codepen.io/herihehe/full/aLwGt
This is a great example of what you want. Look at the difference between contain and cover. Contain shows the actual size of the image. Cover "covers" the area
Upvotes: 3