Skip to content

Commit

Permalink
fix: support CSS custom properties in style attribute (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyubisation committed Jun 11, 2023
1 parent b154c17 commit a26c365
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/jsx-dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>(node).style.setProperty(key, val)
} else if (__FULL_BUILD__ && isNumber(val) && isUnitlessNumber[key] !== 0) {
cast<HTMLElement>(node).style[key] = val + "px"
} else {
cast<HTMLElement>(node).style[key] = val
Expand Down
12 changes: 12 additions & 0 deletions test/test-css.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,16 @@ describe("CSS", () => {
testUnitless("WebkitFlex")
testUnitless("MozFlex")
})

it("supports CSS custom properties (variables)", () => {
const test = (key: string, value: string) =>
expect((<div style={{ [key]: value }} />).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")
})
})

0 comments on commit a26c365

Please sign in to comment.