@diddledan/proportional-height-box
Version:
Web component to resize child element to proportional height based on the width similar to fitvids
69 lines (68 loc) • 2.35 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { LitElement, html, css, property } from 'lit-element';
/**
* proportional-height-box
*
* A block-level element that resizes proportionally, based on code from fitvids.js (http://fitvidsjs.com/)
*
* The `width` and `height` parameters specify a proportional ratio, **not the exact size**.
*
* @demo demo/index.html
*/
class ProportionalHeightBox extends LitElement {
constructor() {
super(...arguments);
/* The width proportion of the desired aspect ratio */
this.width = 4;
/* The height proportion of the desired aspect ratio */
this.height = 3;
}
render() {
return html `
<div id="proportional" style="${this.computeStyle(this.width, this.height)}">
<slot></slot>
</div>
`;
}
/**
* Computes the CSS styling
* @param {number} width The width portion of the aspect ratio
* @param {number} height The height portion of the aspect ratio
*/
computeStyle(width, height) {
var ratio = (height / width) * 100;
return `padding-top: ${ratio}%`;
}
}
ProportionalHeightBox.styles = [
css `
:host {
display: block;
width: 100%;
}
#proportional {
position: relative;
display: block;
height: 0;
}
#proportional > ::slotted(*) {
position: absolute;
display: block;
width: 100%;
height: 100%;
top: 0;
}
`
];
__decorate([
property({ type: Number })
], ProportionalHeightBox.prototype, "width", void 0);
__decorate([
property({ type: Number })
], ProportionalHeightBox.prototype, "height", void 0);
customElements.define('proportional-height-box', ProportionalHeightBox);