Skip to content

Instantly share code, notes, and snippets.

@ralgh
Last active March 27, 2016 16:23
Show Gist options
  • Save ralgh/4711695 to your computer and use it in GitHub Desktop.
Save ralgh/4711695 to your computer and use it in GitHub Desktop.
CSS image crop. Forces image to 4:3 aspect ratio cropping at the middle. http://dabblet.com/gist/4711695
/**
* CSS image crop. Forces image to 4:3 aspect ratio cropping at the middle.
* http://dabblet.com/gist/4711695
*/
.img-crop,
.img-crop img{
width: 100%; /* gotta be responsive these days */
}
.img-crop{
background-color: #ededed; /* some background color for short images */
overflow: hidden;
/* remove white-space for inline-block elements */
letter-spacing: -0.31em; /* webkit */
*letter-spacing: normal; /* reset IE < 8 */
word-spacing: -0.43em; /* IE < 8 && gecko */
}
.img-crop:before,
.img-crop img{
/* vertically center the image */
display: inline-block;
vertical-align: middle;
}
.img-crop:before{
/* pseudo element to vertically align image to */
content: "";
/* Magic Number */
/* Set this to your desired height(to width) ratio */
padding-top: 75%; /* % of original image width */
}
.img-crop img{
/* removes(sorta) image from the flow */
padding-left: 100%;
margin: -999em -100%;
}
/* For layout */
/* Ignore this */
img{
max-width: 100%;
}
.row{
clear: both;
}
.span50{
width: 50%;
}
.row{
letter-spacing: -0.31em; /* webkit */
*letter-spacing: normal; /* reset IE < 8 */
word-spacing: -0.43em; /* IE < 8 && gecko */
}
.row > * {
/*reset letter and word spacing for inline-blocks*/
letter-spacing: normal;
word-spacing: normal;
}
.row:before{
/* helps vertically align children*/
content:"";
height: 100%;
margin-left: -1px;
width:1px;
}
.row > * ,
.row:before{
display: inline-block;
*display: inline; *zoom: 1; /* ie7 hack */
float: none;
vertical-align: middle;
}
<!-- content to be placed inside <body>…</body> -->
<div class="row">
<div class="span50">
<h1>Original Image</h1>
</div>
<div class="span50">
<h1>Cropped 4:3</h1>
</div>
</div>
<div class="row">
<div class="span50">
<img src="http://www.share-international.org/magazine/old_issues/2010/images/201003_crop_circle2.jpg" alt="crop">
</div>
<div class="span50">
<div class="img-crop ratio-4-to-3">
<img src="http://www.share-international.org/magazine/old_issues/2010/images/201003_crop_circle2.jpg" alt="crop cropped">
</div>
</div>
</div>
// alert('Hello world!');
{"view":"split-vertical","fontsize":"100","seethrough":"","prefixfree":"1","page":"all"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment