CSS: A New Kind Of JavaScript

node.style.color = 'red';
const nodes = document.querySelectorAll('p');
Array.prototype.forEach.call(nodes, node => {
node.style.color = 'red';
});
const nodes = document.querySelectorAll('p, li, dd');
node.style.color = 'red';
node.style.backgroundColor = 'black';
node.style.padding = '1rem';
// etc.
node.style.cssText = 'color: red; background-color: black; padding: 1rem;';
Element.prototype.styles = function(attrs) {
Object.keys(attrs).forEach(attr => {
this.style[attr] = attrs[attr];
});
}
node.styles({
'color': 'red',
'backgroundColor': 'black',
'padding': '1rem'
});
const disableds = document.querySelectorAll('[disabled]');Array.prototype.forEach.call(disableds, disabled => {
disabled.styles({
'opacity': '0.5',
'cursor': 'not-allowed'
});
});
button.disabled = true;
button.style // nothing new here
const button = document.querySelector('button');var config = { attributes: true }var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'attributes') {
if (button.disabled) {
button.styles({
'opacity': '0.5',
'cursor': 'not-allowed'
});
}
}
}
}
var observer = new MutationObserver(callback);observer.observe(button, config);

CSS

CSS is a declarative subset of JavaScript, optimized for styling tasks. A CSS file takes the .css extension and, importantly, is parsed completely separately to standard JavaScript files. With CSS it’s finally possible to separate style from behavior. You can brand your applications without having to touch your business logic!

Syntactic sugar

One of the first things you’ll notice is the cleaner syntax, which fans of CoffeeScript will appreciate:

[disabled] {
opacity: 0.5;
cursor: not-allowed;
}

The cascade

CSS stands for Cascading Style Sheets. The cascading part is perhaps its best feature. Consider the following CSS.

button {
background-color: blue;
cursor: pointer;
}
[disabled] {
cursor: not-allowed;
}

Resilience

When styling with JavaScript, any unrecognized style properties or syntax mistakes will cease the parsing of the script. Any ensuing styles or interactions will simply be dropped en masse and your whole application will fall over.

Conclusion

A good sign that a technology is not fit for purpose is how much we have to rely on workarounds and best practices to get by. Another sign is just how much code we have to write in order to get simple things done. When it comes to styling, JavaScript is that technology.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Heydon

Heydon

I often eat rice and do not own an Audi. I know CSS and accessibility. I have a blog about inclusive interaction design: https://inclusive-components.design