简体   繁体   中英

Dynamically crop (or mask?) all images to height of shortest image with CSS and/or JS?

So I have a grid of products in an e-commerce environment, and the heights of each grid cell are determined by the heights of the photographs. Widths are always the same when displayed in the grid, but some pictures manage to be taller.

I'm trying to figure out the easiest way (aside from cropping them all manually) to dynamically determine the height of the shortest photo of a certain class, then crop or mask all photos to that height?

Here's a very rudimentary example of how that code might look. Imagine there is a CSS rule that sets each div of class item to a 25% width and they are displayed inline. In this case, as in mine, images with aspect ratios that aren't equal will be taller or shorter than their neighbors.

<div class="row">
  <div class="item">
    <img src="..."/>
  </div>
  <div class="item">
    <img src="..."/>
  </div>
  <div class="item">
    <img src="..."/>
  </div>
  <div class="item">
    <img src="..."/>
  </div>
</div>

There are a couple of ways to do it you can absolutely position the image in a relative positioned div or you can just set the div to have a background of your image. If your images have extreme varying sizes you may want to go with the background method. If not you may want to go with positioning them absolutely. Whatever works best for you. Here is example css:

.item{
  position:relative;
  padding-bottom:20%; /*padding-bottom for height*/
  overflow:hidden;
}
img{
  position:absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width:100%;
}

/* background method properties */
.item{
  background-size:cover !Importqnt;
  background-position: center !Important;
}

Then for you absolute positioning you can use the markup in your example

<div class="row">
  <div class="item">
    <img src="..."/>
  </div>
  <div class="item">
    <img src="..."/>
  </div>
  <div class="item">
    <img src="..."/>
  </div>
  <div class="item">
    <img src="..."/>
  </div>
</div>

For background you can set the background for each element

<div class="item" style="background:url('...')"></div>

Here is a fiddle Fiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM