Skip to content

Instantly share code, notes, and snippets.

@Septdir
Created Feb 11, 2021
Embed
What would you like to do?
Ratio height for ellements
<div class="block-1" ratio-height="4:3">
Block 4:3 width 250<br/>
<em>ratio-height="4:3"</em>
</div>
<div class="block-2" ratio-height="16:9">
Block 16:9 width 500<br/>
<em>ratio-height="16:9"</em>
</div>
<div class="block-3" ratio-height="1:1">
Block 1:1 width 750<br/>
<em>ratio-height="4:3"</em>
</div>
<style>
.block-1 {
width: 250px;
background: red;
padding: 5px;
color: #FFF;
margin-bottom: 10px;
}
.block-2 {
width: 500px;
background: green;
padding: 5px;
color: #FFF;
margin-bottom: 10px;
}
.block-3 {
width: 750px;
background: blue;
padding: 5px;
color: #FFF;
}
</style>
<script>
function setRatioHeight() {
document.querySelectorAll('[ratio-height]').forEach(function (element) {
let data = element.getAttribute('ratio-height').match(/(\d+):(\d+)/);
if (data) {
let width = data[1],
height = data[2];
if (width && height) {
element.style.height = Math.round((element.getBoundingClientRect().width / width) * height) + 'px';
}
} else {
console.error('data-ratio-height syntax error');
}
});
}
document.addEventListener('DOMContentLoaded', function () {
setRatioHeight();
});
window.addEventListener('resize', function () {
setRatioHeight();
});
</script>
function setRatioHeight() {
document.querySelectorAll('[ratio-height]').forEach(function (element) {
let data = element.getAttribute('ratio-height').match(/(\d+):(\d+)/);
if (data) {
let width = data[1],
height = data[2];
if (width && height) {
element.style.height = Math.round((element.getBoundingClientRect().width / width) * height) + 'px';
}
} else {
console.error('data-ratio-height syntax error');
}
});
}
document.addEventListener('DOMContentLoaded', function () {
setRatioHeight();
});
window.addEventListener('resize', function () {
setRatioHeight();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment