In very advanced cases, you may wish to be able to use a component text property to force styles into the component, for example a button color override.
The approach Sygnal uses here is to;
- Create a custom attribute on an element inside of the component, that begins with
var-
- Bind it to a component property
- Use the variable ( name after the
var-
prefix ) in any styling you want
On page load, the script locates those custom attributes only within the component, and then sets the CSS var accordingly only on that designated element.
This gives you a lot of control as you can override specific variables within specific elements, from component properties.
Unfortunately since this requires code, the effect of the property will only be seen in the published site, and not in the designer.
Code
Place this in an embed inside of the component, just inside of the outermost element.
<script>
// This script will identify its <script> tag in the DOM, locate its immediate parent, and create CSS variables based on custom attributes that start with 'var-'.
(function() {
// Identify the script element
const currentScript = document.currentScript;
if (!currentScript) return;
// Identify the immediate parent element of the script
const parentElement = currentScript.parentElement.parentElement;
if (!parentElement) return;
// Include the parent element itself and any child elements that contain an attribute beginning with 'var-'
const varElements = [parentElement, ...parentElement.querySelectorAll('[*|var-]')];
varElements.forEach((varElement) => {
// Iterate over all attributes of the var element
Array.from(varElement.attributes).forEach((attr) => {
// Only consider attributes that start with 'var-'
if (!attr.name.startsWith('var-')) return;
// Construct the CSS variable name from the attribute name, excluding 'var-' part
const cssVariableName = `--${attr.name.slice(4)}`;
const cssVariableValue = attr.value;
// Apply the CSS variable to the var element directly
varElement.style.setProperty(cssVariableName, cssVariableValue);
});
});
})();
</script>
Often we'll use the variable directly in custom CSS as well since it makes it easy to specify default values when the var is not utilized.
For example;
<style>
.hero-image, .lib-sygnal--hero-image {
object-position: var(--pos-horizontal, 50%) var(--pos-vertical, 50%);
}
</style>
FAQs
Answers to frequently asked questions.