[]previous and next page

Inline styles

Inline styles in the Styling guide.

For agentsUpdated

style takes a CSS text string or an object. Object keys may be camelCase or kebab-case, and custom properties (--name) are supported. null, undefined and false as a value remove that property; as the whole style they remove the attribute.

src/meter.tsxtsx
import { useStore } from "@shadow-js/core";

export function Meter() {
  const [percent, setPercent] = useStore(25);
  return (
    <div
      class="meter"
      style={{
        "--fill": `${percent()}%`,
        backgroundColor: percent() > 50 ? "green" : "tomato",
        opacity: percent() === 0 ? null : 1,
        width: "10rem",
      }}
    >
      <button type="button" onClick={() => setPercent((value) => value + 30)}>
        more
      </button>
    </div>
  );
}

Things to know:

  • A number is in pixels, as in React: width: 10 is 10px, and 0 stays 0. The unitless properties take the bare number (opacity, z-index, flex-grow, line-height, font-weight, stroke-width, ...), and a custom property (--gap) never gets a unit. A string is written as it is, so use one for other units: width: "50%", width: \${w()}px``.
  • The style object is diffed against the previous one. Properties that vanish from the object are removed with removeProperty; a change of only one key writes only that key.
  • A string style replaces cssText as a whole. Switching a style between a string and an object clears the string first.
  • style:name={value} sets one property and is the cheapest binding for a single value, for example style:width={${w()}px}. The name is written in kebab-case (style:background-color); it must be a valid JSX name, so a custom property such as --accent cannot be written this way. Use the style object for custom properties.
src/swatch.tsxtsx
import { useStore } from "@shadow-js/core";

export function Swatch() {
  const [color, setColor] = useStore("rebeccapurple");
  return (
    <button
      type="button"
      class="swatch"
      style:background-color={color()}
      style:opacity={0.5}
      onClick={() => setColor("teal")}
    >
      pick
    </button>
  );
}

The reference for the runtime helpers the compiler emits is className, classList, style and setStyleProperty.