Last Updated: September 21, 2016
·
1.247K
· el_rod

SCSS / Stylus - Aspect Ratio Calculation Mixin

Given an element with a width of x and a height of y.

Note written in SCSS syntax but works in stylus. But can equally represented in sass.

  @mixin aspect-ratio($width, $height) {
    position: relative;
    height: auto;
    &:before {
      display: block;
      content: "";
      width: 100%;
      padding-top: ($height / $width) * 100%;
    }
    & > .content, 
    & > .section-heading, 
    & > img,
    & > div,
    & > svg,
    & > path {
      display: block;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }
}

If you now include it in a style like
@include aspect-ratio(x, y)

This will give you the exact responsive aspect ratio for the given width of the block you are calling it on. It also can target children blocks to make them position absolutely.

To summarize, you can target an element and add a background to it, you can add a child element with the same aspect ratio and have that element positioned in absolute center.

Right now Im just targeting these child elements.

& > .content, 
& > .section-heading, 
& > img,
& > div,
& > svg,
& > path

Stylus version

aspect-ratio($width, $height)
  position relative
  height: auto
  &:before 
    display: block
    content ""
    width 100%
    padding-top ($height / $width) * 100%
  & > .content, 
  & > .section-heading, 
  & > img,
  & > div,
  & > svg,
  & > path
    display block
    position absolute
    top 0
    left 0
    right 0
    bottom 0

Include it

aspect-ratio(x,y)