In some scenarios it's viable to just print out a CSS custom property value to debug. In cases where the value is a non-integer number, it's possible to achieve that with counters. Even if the value is not initially an integer, it's possible to automagically convert it using Houdini API.
Using counters to print custom properties
It's pretty straightforward and well-defined how to print out a scalar integer using CSS counters.
Just by looking at the MDN documentation we can see that we can use counter-reset
and content
properties to print out a value of a counter:
.debug {
--variable: 1280;
&::before {
counter-reset: var var(--variable);
content: counter(var);
}
}
How about more complex values?
Using counters to print non-scalar custom properties
Let's assume that we want to print out the width of the .wide-boy
element:
<div class="wide-boy">
The wide boy.
</div>
.wide-boy {
width: 80%;
}
For that, we can leverage a few hacks features of CSS. Here's the final result:
<div class="wide-boy">
The wide boy.
<div class="debug"></div>
</div>
@property --width-in-px {
syntax: "<length>";
inherits: true;
initial-value: 0;
}
.wide-boy {
width: 80%;
container-type: inline-size;
}
.debug {
/* Transform cqi to px */
--width-in-px: 100cqi;
/* Transform px to scalar */
--width-in-scalar: tan(atan2(var(--width-in-px), 1px));
&::before {
counter-reset: width var(--width-in-scalar);
content: counter(width);
}
}
Step-by-step explanation
The first major step is a neat feature of the Houdini API. When you save a dimensional value (like % or cqi) into a custom property registered with the <length>
syntax, CSS automagically converts it to a computed pixel value for you.
@property --width-in-px {
syntax: "<length>";
inherits: true;
initial-value: 0;
}
As the name suggests writing 100cqi
into the --width-in-px
property will result in dynamic conversion to pixels.
The next step is converting the pixel value to a unitless number. This is done with the tan(atan2(...))
trick first described by Jane Ori, and a little bit by me
Same as we do in regular calculation, dividing two values of the same dimension results in a scalar value.
In this case the division is done by tan(atan2(Xpx, 1px))
.debug {
/* ... */
--width-in-scalar: tan(atan2(var(--width-in-px), 1px));
}
Finally, we can use the print value same as we did before, using counter-reset
and content
properties
.debug {
/* ... */
&::before {
counter-reset: width var(--width-in-scalar);
content: counter(width);
}
}
Playground
DevTools to the rescue
Instead of printing out the value in the DOM, you can also use Chrome DevTools to inspect it. It's quite new feature available only in chromium-based browsers.
To preview the current value of a custom property, you need to hover over calc
or var
in the Styles panel, and the whole calculation will be displayed in a tooltip step-by-step.
