Last active
August 29, 2015 14:18
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | |
}) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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