CSS variables

by Raffi Hovhannesian

HTML

<h1>
  Sample
</h1>

<ul class="menu">
  <li>item 1</li>
  <li class="selected">item 2</li>
  <li>item 3</li>
  <li>item 4</li>
  <li>item 5</li>
</ul>

Highlight color: <a href="#">Test Link</a>
<input type="text" value="" id="textHighlight" />
<br/>

<input type="button" id="changeToRed" class="button" value="Change to red" />

CSS

/*
 * Variables
 */
:root {
    /*
     * Colors
     */
    --white: #ffffff;
    --black: #000;
    --primary-color: #e74c3c;
    --secondary-color: #ccddee;
    --success-color: green;
    --danger-color: #ff0000;
    --link-color: var(--primary-color);
    --link-hover-color: lighten(var(--link-color));

    /*
     * Typography
     */
    --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    --font-size: 1.5rem;
}

/*
 * Base
 */
html {
    font-size: 62.5%;
}

body {
    font-size: var(--font-size);
    line-height: 1.5;
    font-weight: 400;
    font-family: var(--font-family);
    color: var(--black);
}

/************************************
 *
 * Typography
 *
 ************************************/

/*
 * Headers
 */
h1, h2, h3, h4, h5 {
    margin-top: 0;
    margin-bottom: 2rem;
    font-weight: 700;
}

h1 {
    font-size: 4.0rem;
    line-height: 1.2;
}

h2 {
    font-size: 3.6rem;
    line-height: 1.25;
}

h3 {
    font-size: 3rem;
    line-height: 1.3;
}

h4 {
    font-size: 2.4rem;
    line-height: 1.35;
}

h5 {
    font-size: 1.8rem;
    line-height: 1.5;
}

h6 {
    font-size: 1.5rem;
    line-height: 1.6;
}

/*
 * Links
 */
a {
  text-decoration: none;
  color: var(--link-color);
}
a:hover, a:focus {
  text-decoration: underline;
  filter: brightness(70%);
}

JavaScript

// show CSS variable value
var bodyStyles = window.getComputedStyle(document.body);
var colHighlight =  String(bodyStyles.getPropertyValue('--colHighlight'));
var text = document.getElementById('textHighlight');
text.value = colHighlight;

// hook on click
document.getElementById('changeToRed').addEventListener('click', function() {
  // change CSS variable value
  document.body.style.setProperty('--colHighlight', '#ff0000');
});