/dom-max-size

Determine the maximum scalable dimensions of an HTMLElement.

Primary LanguageJavaScriptMIT LicenseMIT

dom-max-size NPM Version File Size Build Status Coverage Status Dependency Monitor

Determine the maximum scalable dimensions of an HTMLElement.

This library works by prepending a largely sized child element to the target element and forcing a re-layout. As such, void elements are not supported because they can never contain that child. Also, elements with a shadowRoot are not automatically supported because the light tree is not rendered, however there is a work-around (see below).

For the sake of performance, be conservative when using this library.

Installation

Node.js >= 10 is required. To install, type this at the command line:

npm install dom-max-size

Importing

ES Module:

import {getMaxHeight, getMaxSize, getMaxWidth} from 'dom-max-size';

CommonJS Module:

const {getMaxHeight, getMaxSize, getMaxWidth} = require('dom-max-size');

Usage

Get the maximum that the web browser can possibly allow for any element:

getMaxHeight(); //-> 33554428, in Chrome 75.x
getMaxWidth(); //-> 33554428, in Chrome 75.x
getMaxSize(); //-> {height:33554428, width:33554428} in Chrome 75.x

Get the maximum that an element can scale to within the limitations of itself and its parents:

<div style="display:flex; max-height:500px; max-width:250px">
  <div id="target" style="width:50%"></div>
</div>
const target = document.getElementById('target');
getMaxHeight(target); //-> 500
getMaxWidth(target); //-> 125

When working with an element that is resized by its descendants, you'll need to provide a reference to all of them:

<div style="display:flex; max-height:500px">
  <div id="target">
    <div id="sizerA"></div>
    <div id="sizerB"></div>
  </div>
</div>
const target = document.getElementById('target');
const sizerA = document.getElementById('sizerA');
const sizerB = document.getElementById('sizerB');
getMaxHeight(target, sizerA, sizerB); //-> 500

The above example also applies when working with a shadowRoot:

const target = document.getElementById('target');
const sizer = target.shadowRoot.querySelector('#sizer');
getMaxHeight(target, sizer); //-> number

Sizing Fixture

If the temporary sizing element is not behaving as expected, resulting in incorrectly returned values, it is possible that it's caused by a CSS complication. While you should probably create an issue, you can—at least temporarily—add any necessary styles via:

target-element > [data-sizing-fixture] {
  /* … */
}

Compatibility

Depending on your target browsers, you may need polyfills/shims for the following: