Skip to content

Instantly share code, notes, and snippets.

@engelfrost
Last active October 15, 2015 12:34
Show Gist options
  • Save engelfrost/c044467273642a54a7e9 to your computer and use it in GitHub Desktop.
Save engelfrost/c044467273642a54a7e9 to your computer and use it in GitHub Desktop.
ZbEWXv
<div class="tws-img">
<div class="tws-img--container"><!--
no whitespace
--><img src="http://placehold.it/600x100" srcset="" alt="" class="tws-img--image"><!--
no whitespace
--></div>
<img src="https://upload.wikimedia.org/wikipedia/commons/c/ce/Transparent.gif" class="tws-img--proportions">
</div>
body {
width: 300px;
}
.tws-img {
position: relative;
width: 100%;
display: inline-block;
float: left; /* removes extra height pixels */
}
.tws-img--proportions {
/* An image with the right proportions. */
width: 100%;
visibility: hidden;
float: left; /* removes extra height pixels */
}
.tws-img--container {
position: absolute;
/* Horizontally align the content to cause a letterbox effect with tall images */
text-align: center;
/* Stretch to size of parent */
top: 0;
left: 0;
right: 0;
bottom: 0;
/* Make background transparent to avoid unwanted pixel lines */
background: transparent;
}
.tws-img--container:before {
/* Use a 0px wide speudo element with 100% height and middle align with the image. This causes a letter-box effect with wide images. */
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
width: 0;
}
.tws-img--image {
display: inline-block;
vertical-align: middle;
/* The image must always be contained within its container */
max-height: 100%;
max-width: 100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment