I'm trying to use knockout's style binding to add CSS3 variables to some div
elements, which are then used in our CSS to compute the final styles.
Example:
var viewModel = function ViewModel() {
this.randomColor = ko.computed(function() {
// Random color thanks to @paul_irish
return "#" + Math.floor(Math.random() * 16777215).toString(16);
});
}();
ko.applyBindings(viewModel);
h2 {
/* default fall-back color: */
--random-colour: #666;
color: var(--random-colour);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<h2 data-bind="style: {'--random-colour': randomColor}">This should receive a random text color.</h2>
http://jsfiddle.net/tujhxdmc/5/
I would expect it to apply the css variable in a style tag, but instead it just seems to be ignored. The surrounding bindings and bindings using standard CSS properties are all working as expected, so I'm certain that it's a problem with CSS variables.
Knockout's documentation states:
If you want to apply a font-weight or text-decoration style, or any other style whose name isn’t a legal JavaScript identifier (e.g., because it contains a hyphen), you must use the JavaScript name for that style. For example,
- Don’t write { font-weight: someValue }; do write { fontWeight: someValue }
But that doesn't work for CSS variables (which must be proceeded by a double-hyphen).
How do you use CSS variables in Knockout's style binding?