Skip to content

Instantly share code, notes, and snippets.

@nemzes
Created April 12, 2018 11:30
Show Gist options
  • Save nemzes/cf3ffb8d50a1760a9ac7c5ae9706cb94 to your computer and use it in GitHub Desktop.
Save nemzes/cf3ffb8d50a1760a9ac7c5ae9706cb94 to your computer and use it in GitHub Desktop.
Fluid images with aspect ratio
<html>
<body>
<style>
.fluid-img {
width: 100%;
overflow: hidden;
position: relative;
outline: 1px solid rebeccapurple; /* remove */
}
.fluid-img-inner {
position: relative;
}
.fluid-img-1-1 .fluid-img-inner {
padding-top: 100%;
}
.fluid-img-4-3 .fluid-img-inner {
padding-top: 75%;
}
.fluid-img-16-9 .fluid-img-inner {
padding-top: 56.25%;
}
.fluid-img-inner > img {
max-width: 100%;
max-height: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
@media only screen and (min-width: 451px) {
.logo-img {
width: 16rem; /* adjust size as needed for breakpoint */
}
}
</style>
<h2>1:1, landscape image</h2>
<div class="fluid-img fluid-img-1-1 logo-img">
<div class="fluid-img-inner">
<img src="http://www.placepuppy.net/400/250" />
</div>
</div>
<h2>1:1, portrait image</h2>
<div class="fluid-img fluid-img-1-1 logo-img">
<div class="fluid-img-inner">
<img src="http://www.placepuppy.net/250/400" />
</div>
</div>
<h2>4:3, landscape image</h2>
<div class="fluid-img fluid-img-4-3 logo-img">
<div class="fluid-img-inner">
<img src="http://www.placepuppy.net/400/250" />
</div>
</div>
<h2>4:3, portrait image</h2>
<div class="fluid-img fluid-img-4-3 logo-img">
<div class="fluid-img-inner">
<img src="http://www.placepuppy.net/250/400" />
</div>
</div>
<h2>16:9, landscape image</h2>
<div class="fluid-img fluid-img-16-9 logo-img">
<div class="fluid-img-inner">
<img src="http://www.placepuppy.net/400/250" />
</div>
</div>
<h2>16:9, portrait image</h2>
<div class="fluid-img fluid-img-16-9 logo-img">
<div class="fluid-img-inner">
<img src="http://www.placepuppy.net/250/400" />
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment