Skip to content

Instantly share code, notes, and snippets.

@jongacnik
Last active August 29, 2015 14:18
Show Gist options
  • Save jongacnik/b2adb73c85a845590078 to your computer and use it in GitHub Desktop.
Save jongacnik/b2adb73c85a845590078 to your computer and use it in GitHub Desktop.
Object Fitter — Test element against an aspect ratio, depending on result add handy attribute to elements
var iselement = require('is-element')
module.exports = function(opts) {
var testRatio
if (iselement(opts.tester)) {
testRatio = opts.tester.clientHeight / opts.tester.clientWidth
} else {
testRatio = window.innerHeight / window.innerWidth
}
if (testRatio <= opts.ratio) {
[].forEach.call(opts.fitters, function(v, i) {
v.setAttribute('data-fit', 'width')
})
} else {
[].forEach.call(opts.fitters, function(v, i) {
v.setAttribute('data-fit', 'height')
})
}
}
[data-fit] {
position: relative;
}
[data-fit] img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
[data-fit="height"] img {
height: 100%;
width: auto;
}
[data-fit="width"] img {
width: 100%;
height: auto;
}
var fitter = require('./object-fitter')
fitter({
'tester' : document.querySelector('[data-fit]'),
'fitters' : document.querySelectorAll('[data-fit]'),
'ratio' : 9/16
})
/**
* If the aspect ratio of the first [data-fit] element is less
* than 9/16 data-fit="width" will be set on all [data-fit] elements,
* otherwise data-fit="height" will be set. You can then use css to
* get images/videos to cover/contain the [data-fit] elements easily.
* /
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment