Wednesday, October 12, 2016

Center and crop thumbnails with CSS

Here is a handy CSS centering technique I first noticed in the WordPress media library, where it is used to centre and crop irregularly sized thumbnails within a square container.
cropped-thumbnails
The technique uses CSS3 transforms, so it works in all modern browsers, including IE9 and above.
<div class="thumbnail">
  <img src="landscape-img.jpg" alt="Image" />
</div>
<div class="thumbnail">
  <img src="portrait-img.jpg" class="portrait" alt="Image" />
</div>
.thumbnail {
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
}
.thumbnail img {
  position: absolute;
  left: 50%;
  top: 50%;
  height: 100%;
  width: auto;
  -webkit-transform: translate(-50%,-50%);
      -ms-transform: translate(-50%,-50%);
          transform: translate(-50%,-50%);
}
.thumbnail img.portrait {
  width: 100%;
  height: auto;
}
The technique works by positioning the image so that its top left corner is in the centre of its container. Then, a 2D translation moves it up and left by half its own width.
The key here is that the percentage values passed to the translate function are relative to the element, not its container, as would be the case if we were to manipulate the element’s top andleft properties instead.
Note that the portrait format image has the class portrait, so that we can correctly scale it to fill its container.
So there you go. A really simple CSS technique for centering and cropping thumbnails.
Source : http://jonathannicol.com/blog/2014/06/16/centre-crop-thumbnails-with-css/

No comments:

Post a Comment