Skip to content

Instantly share code, notes, and snippets.

@ralgh
Created February 4, 2013 23:23
Show Gist options
  • Select an option

  • Save ralgh/4710684 to your computer and use it in GitHub Desktop.

Select an option

Save ralgh/4710684 to your computer and use it in GitHub Desktop.
CSS image crop. Forces image to 4:3 aspect ratio cropping at the middle.
/**
* CSS image crop. Forces image to 4:3 aspect ratio cropping at the middle.
*/
.img-crop{
background-color: #ededed;
overflow: hidden;
width: 100%;
}
.img-crop img{
width: 100%;
}
.img-crop.ratio-4-to-3{
padding-top: 75%; /* 75% of width(4:3 ratio) */
}
.img-crop.ratio-4-to-3 img{
margin-top: -200%;
padding-top: 75%; /* 75% of width(4:3 ratio) */
margin-bottom: -50%; /* (100% - ratioPercent) * 2 */
}
/* Ignore this */
img{
max-width: 100%;
}
.width-half{
float: left;
width: 50%;
}
<!-- content to be placed inside <body>…</body> --><div class="width-half">
<h1>Original Image</h1>
<img src="http://arrestedmotion.com/wp-content/uploads/2011/11/AM-Ai-Weiwei-bicycles-Taiwan-Absent-TFAM-03.jpg" alt="Lots of bikes">
</div>
<div class="width-half">
<h1>Cropped 4:3</h1>
<div class="img-crop ratio-4-to-3">
<img src="http://arrestedmotion.com/wp-content/uploads/2011/11/AM-Ai-Weiwei-bicycles-Taiwan-Absent-TFAM-03.jpg" alt="Lots of bikes">
</div>
</div>
// alert('Hello world!');
{"view":"split","fontsize":"100","seethrough":"","prefixfree":"1","page":"css"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment