Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created September 5, 2020 16:23
Show Gist options
  • Save tomhodgins/7a1d8fb9f095d43570b121e25ee0e9f6 to your computer and use it in GitHub Desktop.
Save tomhodgins/7a1d8fb9f095d43570b121e25ee0e9f6 to your computer and use it in GitHub Desktop.
<!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>
@tomhodgins
Copy link
Author

Screen Shot 2020-09-05 at 12 21 27 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment