Aspect Ratio Mixin

This JavaScript function lets you to define an aspect ratio for elements.

Syntax

aspectRatio(seelctor, ratio)

Example

Input:

aspectRatio('iframe', 16/9)

Output:

/* iframe { aspect-ratio: 1.77; } */
[data-aspect-ratio-unique="0"] {
  height: 503px;
}

Code

function aspectRatio(selector, ratio) {

  var tag = document.querySelectorAll(selector)
  var style = ''
  var count = 0

  for (var i=0; i < tag.length; i++) {

    var attr = selector.replace(/\W+/g, '')

    tag[i].setAttribute('data-aspect-ratio-' + attr, count)

    style += '\n/* ' + selector + ' { aspect-ratio: ' + ratio + '; } */\n'
             + '[data-aspect-ratio-' + attr + '="' + count + '"] {\n'
             + '  height: ' + (tag[i].offsetWidth / ratio) + 'px;\n'
             + '}\n'

    count++

  }

  return style

}

Techniques Capable