Created
September 5, 2020 16:23
-
-
Save tomhodgins/7a1d8fb9f095d43570b121e25ee0e9f6 to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<title>Aspect Ratio Custom Property</title> | |
<script type=module> | |
// Run on load, resize, and 'reprocess' events | |
[ | |
'load', | |
'resize', | |
'reprocess' | |
].forEach(eventType => | |
window.addEventListener(eventType, processAspectRatioProperties) | |
) | |
// Our runtime for supporting --aspect-ratios | |
function processAspectRatioProperties() { | |
document.querySelectorAll('*').forEach(tag => { | |
const aspectRatio = window.getComputedStyle(tag).getPropertyValue('--aspect-ratio') | |
if (aspectRatio !== "") { | |
const [width, height] = aspectRatio.split('/') | |
tag.style.height = `${ | |
tag.getBoundingClientRect().width / (width / height) | |
}px` | |
} | |
}) | |
} | |
</script> | |
<style> | |
/* Set in CSS */ | |
.square { | |
background: lime; | |
--aspect-ratio: 1/1; | |
} | |
[style*="--aspect-ratio"] { | |
background: hotpink; | |
} | |
</style> | |
<!-- Set in CSS --> | |
<div class=square>Square</div> | |
<!-- Set in DOM --> | |
<div style="--aspect-ratio: 16/9">Sixteen by Nine</div> |
Author
tomhodgins
commented
Sep 5, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment