CSS Variables: how can I set a variable to a value that's present in the HTML?

831 Views Asked by At

In CSS Paged Media, there's a useful function called string-set which allows you to define a string once and use it everywhere:

body {  string-set: warningTextVar attr(data-var-TxtWarning);}

.warning::before {
content: warningTxtVar;
}

HTML:

<body data-var-TxtWarning="Warning: ">
    <p class="warning">this is the warning text.</p>

output (when rendered using Antennahouse Formatter):
Warning: this is the warning text.

I can't get this to work in a browser, because string-set has been deprecated. So I'm looking for a way to replace the 'string-set' function in a browser.

The obvious one would be a variable:

body {--Warning: content attr(data-var-TxtWarning);}

but that doesn't seem to work. I can fill the variable with a string:

body {--Warning: "Warning";}

but when I try to read the attribute value, it fails and the variable remains empty.

1

There are 1 best solutions below

1
Bryce Howitson On

If you're already changing the HTML with a data attribute, why don't you just set the CSS variable from the HTML style attribute?

body {
   --Warning: "warning";
}

body .banner:after {
   content: var(--Warning);
}

and

<body style="--Warning:'New Warning Text';">...</body>