Skip to content

CSS Custom Properties

Boolean CSS variables

To allow display, styling etc. based on predefined variables or conditions that can be changed at runtime.

CSS Logical Operations

From Conditional CSS

css
/* Set boolean values */
.not-operation,
.and-operation,
.or-operation {
  --TRUE: 1;
  --FALSE: 0;
}

/* Set Input values */
.not-operation,
.and-operation,
.or-operation {
  --INPUT: var(--TRUE);
  --INPUT-A: var(--FALSE);
  --INPUT-B: var(--TRUE);
}

NOT operation

css
.not-operation {
  --OUTPUT: calc(1 - var(--INPUT));
}

AND operation

css
.and-operation {
  --OUTPUT: calc(var(--INPUT-A) * var(--INPUT-B));
}

OR operation

css
.or-operation {
  --OUTPUT: min(var(--INPUT-A) + var(--INPUT-B), 1);
}

Deeper tricks

From Pseudo-boolean CSS custom properties

    1. Toggling properties with calc()
css
--icon-visible: 1;
.icon {
  width: calc(16px * var(--icon-visible, 1));
}

/* Later */
--icon-visible: 0;
    1. Toggling with @container style queries (CAREFUL OF BROWSER SUPPORT)
    1. Using @property coalescing

TODO: https://lea.verou.me/blog/2024/css-conditionals-now/

TODO: https://forsethingvild.medium.com/lea-verous-dynamic-css-secrets-takeaways-d281218de60a#6ca0

CSS-Only Type Grinding

Source: CSS-Only Type Grinding: Casting Tokens (sm|md|etc) into Useful Values

Example with custom variant properties:

css
/* 
 * Variant Properties
*/
@property --variant {
  syntax: 'contained | outlined | text';
  initial-value: contained;
  inherits: true;
}

@property --contained {
  syntax: '<integer>';
  initial-value: 1;
  inherits: true;
}

@property --contained-else-0 {
  syntax: 'contained | <integer>';
  initial-value: 0;
  inherits: true;
}

@property --outlined {
  syntax: '<integer>';
  initial-value: 1;
  inherits: true;
}

@property --outlined-else-0 {
  syntax: 'outlined | <integer>';
  initial-value: 0;
  inherits: true;
}

@property --text {
  syntax: '<integer>';
  initial-value: 1;
  inherits: true;
}

@property --text-else-0 {
  syntax: 'text | <integer>';
  initial-value: 0;
  inherits: true;
}

.contained {
  --variant: contained;
}

.outlined {
  --variant: outlined;
}

.text {
  --variant: text;
}

.contained,
.outlined,
.text {
  --contained-else-0: var(--variant);
  --contained: var(--contained-else-0);
  --outlined-else-0: var(--variant);
  --outlined: var(--outlined-else-0);
  --text-else-0: var(--variant);
  --text: var(--text-else-0);
}