0.1.2 • Published 5 years ago

csscalc v0.1.2

Weekly downloads
56
License
MIT
Repository
github
Last release
5 years ago

NPM Version

csscalc

JavaScript library to do math with css units.
Fully typed with typescript.

Currently supported units: px, cm, mm, Q, in, pc, pt, vh, vw, vmin, vmax, rem, %w, %h.

  • Convert between css units
  • Calculate css expressions

Based on https://developer.mozilla.org/en-US/docs/Web/CSS/length

Examples

Calculate what part of screen's width takes specified element:

import { calc } from 'cssunits';

// %w means % of width
calc('100%w / 100vw', element);

Calculate area of element:

calc('100%w * 100%h', element);

Convert pixels to percent of element's width:

convert(100, 'px', '%w', calcCtx(element));

Convert element's width percent to pixels:

convert(50, '%w', 'px', calcCtx(element));

// or

Relative["%w"](50, calcCtx(element));

calc method converts all known units and then invokes js's eval method, so you can use any inline js code in calc.
For example min/max from Math:

calc('Math.max(100%w, 100%h)', element)

API

Absolute map, units -> pixels.

Absoulte = {
    "absolute unit name" -> pixels
}

Relative map, (units, calcContext) -> pixels.

Relative = {
    "relative unit name": (units: number, ctx?: CalcContext) => number
}

UnitRegexpStr, UnitRegexp, UnitRegexpGM - regular expression to find units.

Convert between units:

function convert(count: number, fromUnits: Unit, toUnits: Unit, calcCtx?: CalcContext): number;

Create calc context:

function calcCtx(el?: HTMLElement): CalcContext;

Calculate expression:

function calc(expression: string, el: HTMLElement, ctx?: CalcContext): number;
function calc(expression: string, ctx?: CalcContext): number;

Roadmap

  • Reactive calculations