Saving image proportions

I have a list of images with wrapped text, but the images that I get have different sizes (all more than 150 pixels). I need to crop them to 150x100px, but keep the correct aspect ratio. Can anyone suggest a better way to solve 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; } 
+7
html css
source share
4 answers

As long as you don't want server side cropping, you can add the following css:

 .post img { object-fit: cover; } 

Please check for more possible object-fit values.

+10
source share

As an alternative to Ray answers, you can set the images as background and use:

 background-size: cover; 
+2
source share

The best answer to scaling (as opposed to cropping) is Javascript, which controls the process on the server side and then programmatically sets the width and height in HTML / CSS. When you have different heights and widths, the new scaled width should be calculated relative to the height or vice versa, and sometimes both, and CSS does not provide a mechanism for this.

The math is pretty simple. To meet 150 horizontal requirements:

  • newImageY = 150 / incomingImageX * incomingImageY
  • newimageX = 150

To meet 100 vertical requirements:

  • newImageX = 100 / incomingImageY * incomingImageX
  • newimageY = 100

Then, if the scaled axis is too large for any remaining maximum constraints, you scale the entire image (both X and Y) by the required amount.

For cropping (as opposed to scaling), you come across several problems that you need to solve how to handle. Ideally, you (or the submitter) should decide which part of the image you want to show, and then correctly crop it. Therefore, we are talking about the active code and the corresponding user interface.

For example, there may be cases where images will not fill horizontally, but vertically; cases when it will not be filled vertically, if it is scaled to 150 horizontally, etc.

The bottom line is that “you need to study and process the image” if you want to do it well. CSS is simply not able to do a good job here.

+2
source share

If height and width are not specified, or only one of them, the image will support the expected diet.

max-width and max-height can still be used to limit 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; } 
+1
source share

All Articles