Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created October 26, 2017 22:52
Show Gist options
  • Select an option

  • Save aleclarson/11c9d310605d42feb5322c4fe8f19241 to your computer and use it in GitHub Desktop.

Select an option

Save aleclarson/11c9d310605d42feb5322c4fe8f19241 to your computer and use it in GitHub Desktop.
Javascript-driven CSS rules
const capsRE = /([A-Z])/g;
const $styles = $('<style>').appendTo(document.head);
exports.addRule = function(selector, style) {
$styles.append(formatRule(selector, style));
};
function formatRule(selector, style) {
return [
selector,
' {\n ',
css(style).join('\n '),
'\n}'
].join('');
}
function css(style) {
return Object.keys(style).map(key => {
return key.replace(capsRE, hyphenate) + ': ' + style[key] + ';';
});
}
function hyphenate(caps) {
return '-' + caps[0].toLowerCase();
}
@aleclarson

aleclarson commented Oct 26, 2017

Copy link
Copy Markdown
Author

Naïve example:

const styles = require('./css-rules');

// Increase font size on touch-enabled devices.
if ('ontouchstart' in document.documentElement) {
  styles.addRule('a', {
    fontSize: '16px'
  });
}

All values are converted into strings verbatim. Thus, you must add px manually.

Not yet sure how to yield to stylesheets added via <link rel="stylesheet">. May not be possible? If not, this solution is best for overriding existing styles.

jQuery is used, but not required (obviously).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment