Created
November 7, 2018 10:49
-
-
Save adalberth/9e64c193e5fc1661ee64df1d47c111ab to your computer and use it in GitHub Desktop.
Usefull for video og image backgrounds
This file contains 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
/* | |
const {x,y,width,height} = Cover (elements-width, elements-height, container-width, container-height) | |
element.style.top = y + 'px' | |
element.style.left = x + 'px' | |
element.style.width = width + 'px' | |
element.style.height = height + 'px' | |
* Element will fill out the container like css {background-size: cover} | |
* make container desired dimensions and set to overflow:hidden | |
* make element "relative/absolute" and apply value | |
*/ | |
export default function Cover (w, h, w2 = window.innerWidth, h2 = document.documentElement.clientHeight) { | |
const ratio = h / w | |
const width = (h2 / w2) > ratio ? h2 * (w / h) : w2 | |
const height = width * ratio | |
const x = (w2 - width) * 0.5 | |
const y = (h2 - height) * 0.5 | |
return { | |
x, y, width, height | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment