How to Crop Images with CSS

How to Crop Images with CSS

Small trick to change Images ratio size.

First Method, Cropping Height

Let?s say we have image with ratio size of 1:1 and we want to change it to ratio size of 16:9.

Image for postCropped Image View

Calculate Cropping Size

First calculate how much size you need to crop from the picture:

9/16= 56.25(%) /*image percent size after cropping*/

100?56.25 =43.75(%) /*cropping percent value */

44 / 2 = 21.875(%) /*each side*/

Base HTML & CSS

HTML

<figure> <img src=”image-name.jpg”></figure>

CSS

figure{ width:300px; /*container-width*/ overflow:hidden; /*hide bounds of image */ margin:0; /*reset margin of figure tag*/}figure img{ display:block; /*remove inline-block spaces*/ width:100%; /*make image streatch*/}

Add Cropping Styles

Now just add negative margin to the image

figure img{ /*add to other styles*/ margin:-21.875% 0;}

LIVE DEMO

Second Method, Add Height

Now Let?s go the opposite way. Let?s say we have image with ratio size of 16:9 and we want to change it to ratio size of 1:1.

Image for postCropped Image View

Calculate Additional Size

  • 16/9 = 1.7777 /*missing ratio size for ratio 1:1*/
  • 1.777 * 100 = 177.77(%) /*size for the image before cropping*/
  • 177.77?100 = 77.77 /*additional size that will be cropped*/
  • 77.77/2 = 38.885(%) /*additional size that will be cropped each size*/

Base HTML & CSS

HTML

<figure> <img src=”image-name2.jpg”></figure>

CSS

figure{ width:300px; /*container-width*/ overflow: hidden; /*hide bounds of image */ margin:0; /*reset margin of figure tag*/}figure img{ display:block; /*remove inline-block spaces*/ }

Add Cropping Styles

figure img{ /*add to other styles*/ margin:0 -38.885%; width:177.777%;}

LIVE DEMO

That?s all, I hope you enjoy it.

More CSS Posts I Wrote: CSS Position Sticky ? How It Really Works!New CSS Logical Properties!The New Responsive Design Evolution CSS Architecture for Multiple Websites With SASSThe CSS Grid MethodsBecoming a CSS Grid Ninja!Recommended CSS Videos, Channels and Playlists

Follow me on:My TwitterMy Company

You Can find me in my facebook groups:CSS MastersCSS Masters Israel

15

No Responses

Write a response