From a26c3650d702db7a001295d21e8475543889ef4c Mon Sep 17 00:00:00 2001 From: Lukas Spirig Date: Sun, 11 Jun 2023 10:10:49 +0200 Subject: [PATCH] fix: support CSS custom properties in style attribute (#90) --- src/jsx-dom.ts | 6 +++++- test/test-css.tsx | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/jsx-dom.ts b/src/jsx-dom.ts index 89c7499..846ed7d 100644 --- a/src/jsx-dom.ts +++ b/src/jsx-dom.ts @@ -251,7 +251,11 @@ function style(node: Element & HTMLOrSVGElement, value?: any) { node.setAttribute("style", value) } else if (isObject(value)) { forEach(value, (val, key) => { - if (__FULL_BUILD__ && isNumber(val) && isUnitlessNumber[key] !== 0) { + if (key.indexOf('-') === 0) { + // CSS custom properties (variables) start with `-` (e.g. `--my-variable`) + // and must be assigned via `setProperty`. + cast(node).style.setProperty(key, val) + } else if (__FULL_BUILD__ && isNumber(val) && isUnitlessNumber[key] !== 0) { cast(node).style[key] = val + "px" } else { cast(node).style[key] = val diff --git a/test/test-css.tsx b/test/test-css.tsx index c90ca9e..8db50de 100644 --- a/test/test-css.tsx +++ b/test/test-css.tsx @@ -60,4 +60,16 @@ describe("CSS", () => { testUnitless("WebkitFlex") testUnitless("MozFlex") }) + + it("supports CSS custom properties (variables)", () => { + const test = (key: string, value: string) => + expect((
).style.getPropertyValue(key)).to.equal(value, key) + + test("--my-variable", "1") + test("--my-variable", "1px") + test("--my-variable", "anystring") + test("--myVariable", "1") + test("--myVariable", "1px") + test("--myVariable", "anystring") + }) })