Skip to content

Instantly share code, notes, and snippets.

@ehgoodenough
Last active December 6, 2015 03:51
Show Gist options
  • Save ehgoodenough/7090b36433cbc700fdc7 to your computer and use it in GitHub Desktop.
Save ehgoodenough/7090b36433cbc700fdc7 to your computer and use it in GitHub Desktop.
I wrote this mixin to fix an element to an absolute aspect ratio. It resizes the element relative to the viewport, or ``vw`` and ``vh``.
#frame {
top: 0rem;
left: 0rem;
right: 0rem;
bottom: 0rem;
margin: auto;
position: fixed;
overflow: hidden;
}
@media(min-aspect-ratio: 640 / 360) {
#frame {
font-size: 0.27778vh;
width: 177.77778vh;
height: 100vh;
}
}
@media(max-aspect-ratio: 640 / 360) {
#frame {
font-size: 0.15625vw;
height: 56.25vw;
width: 100vw;
}
}
@mixin aspect-ratio($width, $height) {
top: 0rem;
left: 0rem;
right: 0rem;
bottom: 0rem;
margin: auto;
position: fixed;
overflow: hidden;
@media(min-aspect-ratio: #{$width + "/" + $height}) {
font-size: (($width/$height)*100vh)/$width;
width: ($width/$height)*100vh;
height: 100vh;
}
@media(max-aspect-ratio: #{$width + "/" + $height}) {
font-size: (($height/$width)*100vw)/$height;
height: ($height/$width)*100vw;
width: 100vw;
}
}
#game-frame {
@include aspect-ratio(640, 360);
}
@ehgoodenough
Copy link
Author

If you want, you can support multiple aspect ratios by assigning each to a different class, and then dynamically switching between them.

._16x9 {@include aspect-ratio(640, 360)}
._4x3 {@include aspect-ratio(640, 480)}
._3x2 {@include aspect-ratio(640, 426)}

@ehgoodenough
Copy link
Author

Without fixed aspect ratio

frame1

With fixed aspect ratio

frame2

@ehgoodenough
Copy link
Author

Any children can be positioned in units of em instead of px, since the font-size is likewise relative to the viewport.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment