Reputation: 2449
I have a list of images with text wrapped around but images I receive come in different sizes (all larger than 150px). I need to crop them all to 150x100px but keep correct aspect ratio. Could anyone please suggest the best way of solving this problem? Thanks!
HTML:
<ul>
<div class="post" id="post">
<div>
<li>
<img class="TextWrap" src="{{ picture }}">
<a href="{{ link }}">{{ message }}</a><p>
{{ time }}
</li>
</div>
</ul>
CSS:
.post {
width: 500px;
margin-top: 15px;
float: left;
}
.post img {
width: 150px;
height: 100px;
margin-bottom: 15px;
margin-right: 20px;
}
.TextWrap {
float: left;
}
Upvotes: 14
Views: 13262
Reputation: 1185
When no height and width are specified, or only one of them the picture will keep it's expected ration.
max-width
and max-height
can still be used to limit the the size
.post {
width: 500px;
margin-top: 15px;
float: left;
}
.post img {
max-width: 150px;
max-height: 100px;
margin-bottom: 15px;
margin-right: 20px;
}
.TextWrap {
float: left;
}
Upvotes: 1
Reputation: 2658
The best answer to scaling (as opposed to cropping) is Javascript driving a server-side process and then setting the width and height in the HTML/CSS programatically. When you have varying heights and widths, the newly scaled width has to be calculated relative to the height, or vice-versa, and sometimes both, and CSS doesn't provide a mechanism for this.
The math is pretty simple. To match to a 150 horizontal requirement:
To match to a 100 vertical requirement:
Then, if the scaled axis is too large for any remaining maximum constraints, you scale the entire image (both X and Y) down by the required amount.
For cropping (as opposed to scaling), you face several issues that you have to decide how to handle. Ideally, you (or the submitter) would decide what part of the image you want to show, and then crop intelligently. So we're talking about both active code and an associated UI.
For instance, there can be cases where images won't fill horizontally, but will vertically; cases where it won't fill vertically if scaled to 150 horizontally, etc.
The bottom line is pretty much "you have to examine and process the image" if you want to do this well. CSS just isn't up to doing a good job here.
Upvotes: 2
Reputation: 12400
As an alternative to Ray's answer, you can set the images as backgrounds and use:
background-size: cover;
Upvotes: 2
Reputation: 3189
As long as you do not want server side cropping, you can add following css:
.post img {
object-fit: cover;
}
Please check more possible values for object-fit
Upvotes: 24