css variables (custom properties) + em fonts
by jonahe
HTML
<div>
<div>
<input id="fontSlider" value="16" type="range" min=12 max=30 step="1" />
</div>
<span>Base font size </span><span id="fontSizeOutput">
= 1em
</span>
<hr/>
<div>
<input id="colorPicker" type="color" style="width:85%;">
<span>Background color: </span>
<span id="backgroundColorOutput"></span>
</div>
</div>
<h1>
Demo h1 (3em)
</h1>
<h2>
Demo h2 (2em)
</h2>
<p>
This font is 1 em.
</p>
CSS
:root {
--project-base-font-size: 16px;
/* note that having a space befor the color code resulted in the space being a part of the code.. giving the error "The specified value " #A090E5" does not conform to the required format."" */
--project-primary-color:#A090E5;
}
html {
font-size: var(--project-base-font-size);
}
body {
background-color: var(--project-primary-color);
}
h1 {
font-size: 3em;
}
h2 {
font-size: 2em;
}
p {
font-size: 1em;
}
JavaScript
const slider = document.getElementById("fontSlider");
const output = document.getElementById("fontSizeOutput");
const colorPicker = document.getElementById("colorPicker");
const colorOutput = document.getElementById("backgroundColorOutput");
const defaultColor = getComputedStyle(document.documentElement)
.getPropertyValue('--project-primary-color');
colorOutput.innerHTML = defaultColor;
colorPicker.value = defaultColor;
colorPicker.onchange = function() {
colorOutput.innerHTML = this.value;
document.documentElement.style.setProperty('--project-primary-color', this.value);
}
output.innerHTML = getComputedStyle(document.documentElement)
.getPropertyValue('--project-base-font-size');
slider.oninput = function() {
output.innerHTML = this.value + "px";
document.documentElement.style.setProperty('--project-base-font-size', this.value + "px");
}