Angular — CSS Variables Utility

George Roubie
2 min readOct 23, 2019

In every Front-End project instead of CSS I use SCSS (CSS with super powers), because the features of SCSS are many and helpful in large scale applications.

One of my favorites feature is the SCSS variables, that helps you with the pattern DRY (don’t repeat yourself). But the disadvantage is that these variables are not accesible from the JavaScript.

This problem can be solved with the CSS Variables, also known as CSS Custom Properties.

CSS Variables are entities defined by CSS authors that contain specific values to be reused throughout a document.

I created an Angular Utility (Service) that gets and sets the value of a CSS Variable.

@Injectable()
export class CssVariablesUtility {
public getValue(propertyName: string): string | null {
try {
const root: HTMLElement = document.documentElement;
const value: string =
getComputedStyle(root).getPropertyValue(propertyName);
return value ? value.trim() : null;
} catch(ex) { return null; }
}
public setValue(propertyName: string, newValue: string): void {
try {
const root: HTMLElement = document.documentElement;
root.style.setProperty(propertyName, newValue);
} catch (ex) { }
}
}

You can download the above code from here.

REAL LIFE PROBLEM

Let’s say that you have a top menu in an application, that has a height of 50 pixels. And you want to create a DOM element with JavaScript and the height of this element must be the viewport minus the top menu height.

You can set the height of the element to this: calc(100vh — 50px) . But if the top menu is changed you must also change the height of the JavaScript element and I am pretty sure that you will forget it.

Let’s use CSS Variables and the CSSVariablesUtility to solve this.

In the CSS we will add this:

/* Variables */
:root {
--topmenu-height: 50px;
}
/* Menu */
.top-menu {
height: var(--topmenu-height);
}

And in the JavaScript we will add this:

constructor(
private cssVariablesUtility: CssVariablesUtility
}
ngAfterViewInit() {
const topMenuHeight: number = this.cssVariablesUtility
.getValue('--topmenu-height')
;
el.style.height = `calc(100vh - ${topMenuHeight})`;
}

Now the height of the element is based on the CSS!!!

If you enjoyed this, please Clap it up and give a star to the repository.

--

--

George Roubie

Experienced Software Engineer with more than 10 years of experience, specialized in Front-End Web technologies, with strong foundations in programming.