HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<main>
<h1>Fluid-responsive property calculator</h1>
<p>A full description available on the finished product: <a class=fancyLnk target=_blank title="[new window]" rel="me noopener" href="https://websemantics.uk/tools/responsive-font-calculator/">Fluid-responsive font-size calculator</a>.</p>
<form class=frm>
<fieldset class=frm_fld>
<legend class=-visuallyHidden>Fluid-responsive calulator</legend>
<fieldset class=frm_fld-units>
<div class=grid-units>
<legend class=frm_lgnd-units>Units:</legend>
<div class=flexed-units>
<label class=IN_lbl-radio>
<span class=lbl_txt>PX</span>
<input class=IN_radio type=radio name=unit id=IN_radio_px value=px checked>
<span></span>
</label>
<label class=IN_lbl-radio>
<span class=lbl_txt>REM</span>
<input class=IN_radio type=radio name=unit id=IN_radio_rem value=rem>
<span></span>
</label>
<label class=IN_lbl-radio>
<span class=lbl_txt>EM</span>
<input class=IN_radio type=radio name=unit id=IN_radio_em value=em>
<span></span>
</label>
</div>
</div>
</fieldset>
<div class=grid-selector>
<label class=frm_lbl-selector for=IN_selector>Selector
<small class=lbl_smll>(element, class, id)</small></label>
<input class=IN-selector id=IN_selector type=text value=:root required>
</div>
<div class=grid-property>
<label class=frm_lbl-property for=IN_property>Property
<small class=lbl_smll>(usually font-size)</small></label>
<input class=IN-property id=IN_property type=text value=font-size required>
</div>
<fieldset class=frm_fld-ranges>
<legend class=-visuallyHidden>Ranges:</legend>
<fieldset class=frm_fld-propertyRange>
<div class=grid-propertyRange>
<legend class=frm_lgnd-propertyRange>Range:
<small class=lbl_smll>(of property)</small></legend>
<div class=flexed-fromto>
<label class=frm_lbl for=IN_minFS>from</label>
<input class=IN-minFS id=IN_minFS type=text value=16 required pattern="[0-9]*[.]?[0-9]+">
<label class=frm_lbl for=IN_maxFS>to</label>
<input class=IN-maxFS id=IN_maxFS type=text value=24 required pattern="[0-9]*[.]?[0-9]+">
<span class=units>px</span>
</div>
</div>
</fieldset>
<div class=grid-at aria-hidden=true>
<div></div>
<div class=flexed-fromto>
<span class=spn-hidden>from</span>
<span class=spn-at>@</span>
<span class=spn-hidden>to</span>
<span class=spn-at>@</span>
<span class="units spn-hidden">px</span>
</div>
</div>
<fieldset class=frm_fld>
<div class=grid-viewport>
<legend class=frm_lgnd-viewport>Viewport:
<small class=lbl_smll>(browser width)</small></legend>
<div class=flexed-fromto>
<label class=frm_lbl for=IN_minVW>from</label>
<input class=IN-minVW id=IN_minVW type=text value=768 required pattern="[0-9]*[.]?[0-9]+">
<label class=frm_lbl for=IN_maxVW>to</label>
<input class=IN-maxVW id=IN_maxVW type=text value=1920 required pattern="[0-9]*[.]?[0-9]+">
<span class=units>px</span>
</div>
</div>
</fieldset>
</fieldset>
<fieldset class=frm_fld>
<div class=grid-methods>
<legend class=frm_lgnd-methods>CSS method:</legend>
<div class=flexed-methods>
<label class=IN_lbl-radio-stops>
<span class=lbl_txt>End query</span>
<input class=IN_radio name=method type=radio id=IN_radio_stops value=stops checked>
<span></span>
</label>
<label class=IN_lbl-radio-nostops>
<span class=lbl_txt>No End query</span>
<input class=IN_radio name=method type=radio id=IN_radio_nostops value=nostops>
<span></span>
</label>
<label class=IN_lbl-radio-clamp>
<span class=lbl_txt>Clamp</span>
<input class=IN_radio name=method type=radio id=IN_radio_clamp value=clamp>
<span></span>
</label>
<label class=IN_lbl-radio-minmax>
<span class=lbl_txt>Min-max</span>
<input class=IN_radio name=method type=radio id=IN_radio_minmax value=minmax>
<span></span>
</label>
</div>
</div>
</fieldset>
<fieldset class=frm_fld-options>
<div class=grid-options>
<legend class=frm_lgnd-options>Options:</legend>
<div class=flexed-options>
<label class=IN_lbl-check-comments>
<span class=lbl_txt><span class=-visuallyHidden>Include</span> Comments</span>
<input class=IN_check type=checkbox id=IN_check_comments>
<span></span>
</label>
<label class=IN_lbl-check-safarifix>
<span class=lbl_txt><span class=-visuallyHidden>Include</span> Safari fix</span>
<input class=IN_check type=checkbox id=IN_check_safarifix checked>
<span></span>
</label>
<label class=IN_lbl-check-longhand>
<span class=lbl_txt><span class=-visuallyHidden>Use</span> Longhand <span class=-visuallyHidden>calculation</span></span>
<input class=IN_check type=checkbox id=IN_check_longhand>
<span></span>
</label>
</div>
</div>
</fieldset>
</fieldset>
</form>
<figure class="OUT_fgr shadowlift">
<figcaption class=OUT_cptn>Generated CSS <small>(editable)</small>:</figcaption>
<pre class=OUT_pre><code class="OUT_code language-css" id=resultCSS spellcheck=false contenteditable>
</code></pre>
</figure>
<h2>Update included:</h2>
<ul>
<li>Variable property name</li>
<li>CSS clamp option</li>
<li>CSS min/max option</li>
<li>Safari resize fix option</li>
<li>Longhand calculation option</li>
<li>Settings preserved with localStorage</li>
<li>Improved HTML form semantics</li>
<li>Prevent non-numeric inputs</li>
<li>Grid and Flexbox layout</li>
<li>Limited to 4 decimal places.</li>
</ul>
</main>
<!-- Footer codepen include -->
[[[https://codepen.io/2kool2/pen/mKeeGM]]]
html {
box-sizing: border-box;
/*
Fluidly variable between:
1rem (16px) @ 20rem (320px)
increasing to
2rem (32px) @ 120rem (1920px)
All these font-size settings are equivalent:
*/
/* query */
font-size: calc(1rem + ((1vw - 0.2rem) * 1));
/* longhand */
font-size: calc(1rem + (2 - 1) * ((100vw - 20rem) / (120 - 20)));
/* clamp */
font-size: clamp(1rem, calc(1rem + ((1vw - 0.2rem) * 1)), 2rem);
/* min-max */
font-size: min(max(1rem, calc(1rem + ((1vw - 0.2rem) * 1))), 2rem);
font-size: calc(.8rem + 1vw);
/* Fix Safari bug with viewport units in calc() */
min-height: 0vw;
}
*,
*::before,
*::after {box-sizing: inherit;}
body {
/* Fluidly variable between: 16px @ 320px and 32px @ 1920px */
--space: 1rem;
--spaceAndHalf: calc(var(--space) * 1.5);
--spaceDouble: calc(var(--space) * 2);
--spaceHalf: calc(var(--space) / 2);
--spaceQuarter: calc(var(--space) / 4);
--spaceEighth: calc(var(--space) / 8);
margin: 0;
color: #666;
font-family: sans-serif;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: hsl(269,19%,30%);
background-color: hsla(32,100%,85%,.35);
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg width='100%25' xmlns='http://www.w3.org/2000/svg'%3E%3Cdefs%3E%3Cfilter id='a'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.4'/%3E%3C/filter%3E%3C/defs%3E%3C!-- %3Cpath filter='url(%23a)' opacity='.3' d='M0 0h1200v256H0z'/%3E--%3E%3Crect filter='url(%23a)' opacity='.3' width='100%25' height='100%25'/%3E%3C/svg%3E");
}
::-moz-selection {
color: #fff;
background-color: #000;
}
::selection {
color: #fff;
background-color: #000;
}
main {
max-width: 40rem;
margin: var(--space) auto;
}
h1,h2 {
font-weight: 100;
margin-top: 2rem;
margin-bottom: 1rem;
padding: 0 1rem;
text-align: center;
line-height: 1.2;
}
h2 {font-size: 1.5rem; margin:1.5rem 0 0;}
p,ul {
max-width: 34rem;
margin: 1rem auto;
padding: 0 1rem;
}
ul{
max-width: 19rem;
}
.-visuallyHidden {
position: absolute !important;
clip: rect(1px, 1px, 1px, 1px);
padding: 0 !important;
border: 0 !important;
height: 1px !important;
width: 1px !important;
overflow: hidden;
}
.-noWrap{
white-space: nowrap !important;
}
/* from forms.css */
/* Radios & Checkboxes (Tick boxes) */
[type="radio"],
[type="checkbox"] {
width: 0;
position: absolute;
left: -200rem;
z-index: -1;
}
[type="radio"] + span,
[type="checkbox"] + span {
position: relative;
display: inline-block;
height: 1rem;
padding-right: 1.25rem;
margin-left: 0.382rem;
}
[type="radio"] + span:before,
[type="radio"] + span:after,
[type="checkbox"] + span:before,
[type="checkbox"] + span:after {
content: "";
position: absolute;
transition: transform 0.35s;
}
[type="radio"] + span:before,
[type="radio"] + span:after {
top: .1rem;
left: 0;
width: 1.1rem;
height: 1.1rem;
}
[type="checkbox"] + span:before,
[type="checkbox"] + span:after {
top: .2rem;
left: 0;
width: .9rem;
height: .9rem;
}
[type="radio"] + span:before,
[type="checkbox"] + span:before {
border: .125rem solid #9A9A9A;
background-color: #fff;
}
[type="radio"] + span:before {
border-radius: 3rem;
}
[type="radio"]:checked + span:before,
[type="checkbox"]:checked + span:before {
background-color: #C8FFC8;
border-color: #9c9;
transform: scale(.8);
}
[type="radio"] + span::after,
[type="checkbox"] + span::after {
width: 3rem;
height: 3rem;
top: -.875rem;
left: -1rem;
background-position: center;
background-size: cover;
transform: scale(0);
}
[type="radio"]:checked + span::after,
[type="radio"]:checked + span::after,
[type="checkbox"]:checked + span::after,
[type="checkbox"]:checked + span::after {
transform: scale(1);
}
/* keyboard focus */
[type="radio"]:focus + span::before {
transform: scale(1.25);
border-color: #83B2E3;
}
[type="checkbox"]:focus + span::before {
transform: scale(1.5);
border-color: #83B2E3;
}
/* SVG */
[type="radio"] + span::after,
[type="checkbox"] + span::after {
/*background-image: url(../i/form/valid.svg);*/
background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjM2IiBoZWlnaHQ9IjM2IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogPHRpdGxlPnZhbGlkPC90aXRsZT4KCiA8bWV0YWRhdGEgaWQ9Im1ldGFkYXRhOCI+aW1hZ2Uvc3ZnK3htbDwvbWV0YWRhdGE+CiA8Zz4KICA8dGl0bGU+TGF5ZXIgMTwvdGl0bGU+CiAgPGcgdHJhbnNmb3JtPSJtYXRyaXgoMC4wNzE5NDM0LCAwLCAwLCAtMC4wNzE5NDM0LCAzLjExNDMzLCAxOC45MTcxKSIgaWQ9ImcxMCI+CiAgIDxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDkuNDQ1NDQsIC04LjM5NTk1KSBzY2FsZSgwLjEpIiBpZD0iZzEyIj4KICAgIDxwYXRoIGQ9Im0xMDIzLjY0MzAwNSwzMC40MTM5MjljMjE1Ljk5NTkxMSwtMTM4LjAwMDAwNCAzNzEuOTk1OTExLC00NDkuOTk5OTg5IDM3MS45OTU5MTEsLTQ0OS45OTk5ODljNjcyLjAwNDE1LDEzOTIuMDAwMzA1IDE5MzIuMDA0MTUsMjE2MC4wMDA0ODggMTkzMi4wMDQxNSwyMTYwLjAwMDQ4OGMtMTM0NC4wMDAyNDQsLTEyNDIuMDAwNDg4IC0xOTUwLjAwMDM2NiwtMzAwMCAtMTk1MC4wMDAzNjYsLTMwMDBjLTQ0OS45OTk4NzgsOTA1Ljk5OTUxMiAtNjUzLjk5OTg3OCw4MzkuOTk5NTEyIC02NTMuOTk5ODc4LDgzOS45OTk1MTJsMjk5Ljk5OTkzOSw0NDkuOTk5OTg5IiBpZD0icGF0aDE0IiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGZpbGw9IiMwMzk4NjIiLz4KICAgPC9nPgogIDwvZz4KIDwvZz4KPC9zdmc+);
}
/* Form */
[class^="IN_lbl-check"].-js-disabled {
opacity: 0.5;
}
.frm {
background-color: rgba(255,255,255,.4);
border: 2px dashed #f90;
padding: var(--space);
width: calc(100% - var(--spaceDouble));
max-width: 34rem;
margin: var(--space) auto;
}
[class^="frm_fld"] {
border: 0;
padding: 0;
margin: 0 auto;
}
.frm_fld:first-child {
max-width: 24rem;
margin: 0 auto;
}
/* Titles */
[class^="frm_lgnd"],
.frm_lbl-selector,
.frm_lbl-property {
font-weight: 400;
padding: 0;
}
.lbl_smll {
font-weight: 300;
}
@media (min-width: 30em) {
.frm_lbl-selector,
.frm_lbl-property,
.frm_lgnd-propertyRange,
.frm_lgnd-viewport,
.frm_lgnd-options {
line-height: 1.2;
}
.lbl_smll {
display: block;
}
}
/* Block margins */
.frm {
--blockMarginBottom: var(--spaceAndHalf);
}
.frm_fld-units,
.grid-selector,
.grid-property,
.frm_fld-ranges,
.frm_fld-propertyRange {
margin-bottom: var(--blockMarginBottom);
}
.frm_fld-options {
margin-top: .5rem;
}
@media (min-width: 30em) {
.frm {
--blockMarginBottom: var(--space);
}
.frm_fld-propertyRange {
margin-bottom: 0;
}
}
/* Grid elements */
[class^="grid-"] {
--columns: auto 1fr;
--gridGap: var(--space);
grid-gap: var(--gridGap);
grid-template-columns: var(--columns);
align-items: center;
}
.grid-at {
display: none;
}
@media (min-width: 20em) {
.grid-units {
display: grid;
}
}
@media (min-width: 30em) {
[class^="grid-"] {
--columns: 7.5rem 1fr;
--gridGap: var(--spaceEighth);
display: grid;
}
}
@media (min-width: 32em) {
[class^="grid-"] {
--gridGap: var(--spaceHalf);
}
}
/* Flex elements */
@media (min-width: 20em) {
[class*="flexed"] {
display: flex;
align-content: center;
align-items: center;
justify-content: space-around;
flex-wrap: wrap;
}
.flexed-units {
width: auto;
justify-content: space-between;
}
.flexed-fromto {
max-width: 17rem;
margin: 0 auto;
}
.flexed-options {
text-align: center;
}
}
@media (min-width: 30em) {
.flexed-fromto {
width: auto;
margin: 0;
flex: auto 1 0;
justify-content: space-between;
}
}
/* Text inputs */
[class^="IN-"] {
line-height: inherit;
font-size: inherit;
font-weight: inherit;
padding: .312rem .618rem;
max-width: 100%;
display: block;
outline: 0 solid #9CC9F9;
border: 1px solid #ccc;
transition: box-shadow .3s ease-out, border-color .3s ease-out;
}
[class^="IN-"]:focus {
outline: 0 solid #9CC9F9;
border-color: #9CC9F9;
box-shadow: 0 0 .0625rem .0625rem #9CC9F9;
}
[class^="IN-m"] {
width: 4.5rem;
}
.IN-selector,
.IN-property {
width: 100%;
}
/* Input radio / checkboxes - Units / Options */
[class^="IN_lbl-"] {
display: block;
line-height: 2;
}
@media (min-width: 20em) {
.IN_lbl-radio {
line-height: inherit;
}
}
@media (min-width: 24em) {
.IN_lbl-check {
width: 29.75%;
line-height: 1.3;
}
.IN_lbl-check:first-child {
width: 31.05%;
}
.IN_lbl-check:last-child {
width: 26.7%;
}
}
/* Odd span values for tidy up */
@media (min-width: 30em) {
.spn-hidden {
visibility: hidden;
}
.spn-at {
display: block;
text-align: center;
padding: 0 .618rem;
width: 4.5rem;
}
}
/* Output */
.OUT_ttl {
margin-top: 2.618rem;
}
.OUT_fgr {
margin:1.618rem 0;
padding:0;
}
.OUT_btns {
margin-top: 1.618rem;
}
.OUT_btns.flexed {
justify-content: space-around;
flex-wrap: nowrap;
}
.button.btn-test {
background-color: #236ECE;
}
.options_ttl {
margin-top: 1rem;
}
.btn-copy {
margin-right: .618rem;
}
.button.btn-copied {
background-color: #477343;
border: 1px solid #242424;
}
.OUT_fgr {
margin: var(--spaceDouble) var(--space);
}
code[class*="language-"] {
line-height: 2rem;
}
/* Prism - is used for code highlighting from an external pen: https://codepen.io/2kool2/pen/MEbeEg */
// Force Prism (and fancyLnks) to use light mode:
document.body.setAttribute('data-lightmode', 'light');
const Calculator = (_ => {
'use strict';
// Start - Allow only numeric inputs //
const allowNumericAndControlsKeysOnly = e => {
// function prevents default action on unwanted key pressed.
// Exit this function to allow specific control keys.
// Unfortunately, no paste (CMD V || CTRL V) allowed as it complicates error checking beyond project scope.
if (
(e.which === 65 && e.ctrlKey) || // CTRL A
(e.which === 65 && e.metaKey) || // CMD A
(e.which === 67 && e.ctrlKey) || // CTRL C
(e.which === 67 && e.metaKey) || // CMD C
(e.which > 36 && e.which < 41) || // ARROW KEYS
(e.which === 9 && e.shiftKey) || // SHIFT TAB
e.which === 8 || // TAB
e.which === 9 || // BACKSPACE DEL
e.which === 13 // RETURN
) return;
// Only 0-9, and a single instance of . allowed, otherwise the keypress is ignored
if (!(
(e.which > 47 && e.which < 58) || // 0-9
(e.which === 190 && e.target.value.indexOf('.') === -1) // Only 1 period
)) {
e.preventDefault();
}
};
// Limit to four rounded decimal places.
const sanitize = value => Math.round(value * 10000) / 10000;
const setNumericValue = (value, prop, valueWhenIllegal) => {
value = sanitize(value);
if (isNaN(value) || value === 0) value = valueWhenIllegal;
SETTINGS[prop].set(value); // string
};
const setNumericInputEvents = prop => {
const obj = SETTINGS[prop].obj;
obj.addEventListener('focus', _ => {
obj.addEventListener('keydown', allowNumericAndControlsKeysOnly);
});
obj.addEventListener('blur', e => {
obj.removeEventListener('keydown', allowNumericAndControlsKeysOnly);
setNumericValue(e.target.value, prop, 1);
});
obj.addEventListener('change', e => {
setNumericValue(e.target.value, prop, 1);
});
obj.addEventListener('input', e => {
// Automatically updates valid values as they are typed
const v = e.target.value;
const lc = v.substr(v.length - 1);
// Do not update values which detract from typing numbers
// No update when:
if (
v.length > 0 && // Empty string
v != 0 && // Equals zero (purposefully loose)
lc !== '.' && // Trailing period
!(lc === '0' && e.target.value.indexOf('.') !== -1) // Zero after a period
) {
setNumericValue(e.target.value, prop, 1);
}
});
SETTINGS[prop].set(SETTINGS[prop].value);
};
// End - allow only numeric inputs //
const setNumericInputValues = (prop, value) => {
value = sanitize(value);
SETTINGS[prop].obj.value = value;
SETTINGS[prop].value = value + '';
updateOutput();
};
const setTextInputValue = (prop, value) => {
SETTINGS[prop].obj.value = value;
SETTINGS[prop].value = value;
updateOutput();
};
const radiosUnits = document.querySelectorAll('.IN_radio[name="unit"]');
const radiosMethods = document.querySelectorAll('.IN_radio[name="method"]');
const radiosSet = (set, val) => {
for (const rad of set) {
if (rad.value === val) {
rad.setAttribute('checked', true);
} else {
rad.removeAttribute('checked');
}
}
};
const setCheckedInputValues = (prop, value) => {
value += '';
if (value === 'true') {
SETTINGS[prop].obj.setAttribute('checked', true);
} else {
SETTINGS[prop].obj.removeAttribute('checked');
}
SETTINGS[prop].value = value + '';
updateOutput();
};
const SETTINGS = {
// Each primary key is an input or radio fieldset.
units : {
value : 'px',
previousValue : 'px',
init : _ => {
for (const rad of radiosUnits) {
rad.addEventListener('click', e => SETTINGS.units.set(e.target.value));
// Reset when returning from a back button click
// if (rad.hasAttribute('checked')) rad.click();
}
},
set : value => {
SETTINGS.units.previousValue = SETTINGS.units.value;
SETTINGS.units.value = value;
radiosSet(radiosUnits, value);
convertNumericValues();
updateOutput();
updateUnits();
}
},
selector : {
obj : document.querySelector('.IN-selector'),
value : ':root',
init : _ =>
SETTINGS.selector.obj.addEventListener('input', e => SETTINGS.selector.set(e.target.value)),
set : value => setTextInputValue('selector', value)
},
property : {
obj : document.querySelector('.IN-property'),
value : 'font-size',
init : _ =>
SETTINGS.property.obj.addEventListener('input', e => SETTINGS.property.set(e.target.value)),
set : value => setTextInputValue('property', value)
},
// PROPERTY RANGE
minFS : {
obj : document.querySelector('.IN-minFS'),
value : '16',
init : _ => setNumericInputEvents('minFS'),
set : value => setNumericInputValues('minFS', value)
},
maxFS : {
obj : document.querySelector('.IN-maxFS'),
value : '24',
init : _ => setNumericInputEvents('maxFS'),
set : value => setNumericInputValues('maxFS', value)
},
// VIEWPORT RANGE
minVW : {
obj : document.querySelector('.IN-minVW'),
value : '768',
init : _ => setNumericInputEvents('minVW'),
set : value => setNumericInputValues('minVW', value)
},
maxVW : {
obj : document.querySelector('.IN-maxVW'),
value : '1920',
init : _ => setNumericInputEvents('maxVW'),
set : value => setNumericInputValues('maxVW', value)
},
// CSS METHODS
methods : {
value : 'stops',
init : _ => {
for (const rad of radiosMethods) {
rad.addEventListener('click', e => SETTINGS.methods.set(e.target.value));
// Reset when returning from a back button click
// if (rad.hasAttribute('checked')) rad.click();
}
},
set : value => {
SETTINGS.methods.value = value;
radiosSet(radiosMethods, value);
updateOutput();
}
},
// OPTIONS
comments : {
obj : document.getElementById('IN_check_comments'),
value : 'false',
init : _ =>
SETTINGS.comments.obj.addEventListener('click', _ => SETTINGS.comments.set(!SETTINGS.comments.obj.hasAttribute('checked'))),
set : value => setCheckedInputValues('comments', value)
},
safarifix : {
obj : document.getElementById('IN_check_safarifix'),
value : 'true',
init : _ =>
SETTINGS.safarifix.obj.addEventListener('click', _ => SETTINGS.safarifix.set(!SETTINGS.safarifix.obj.hasAttribute('checked'))),
set : value => setCheckedInputValues('safarifix', value)
},
longhand : {
obj : document.getElementById('IN_check_longhand'),
value : 'false',
init : _ =>
SETTINGS.longhand.obj.addEventListener('click', _ => SETTINGS.longhand.set(!SETTINGS.longhand.obj.hasAttribute('checked'))),
set : value => setCheckedInputValues('longhand', value)
}
};
const OUTPUT = {
text : '',
value : ''
};
// Copy button visuals - processing is an external function
const initCopyBtn = _ => {
const btn = document.getElementById('btn_copy');
if (btn) {
btn.originalText = btn.textContent;
btn.clickedText = btn.textContent.replace('Copy', 'Copied');
}
return btn;
};
const btn_cpy = initCopyBtn();
const resetCopyBtn = _ => {
if (btn_cpy) {
btn_cpy.textContent = btn_cpy.originalText;
btn_cpy.classList.remove('green');
btn_cpy.classList.add('orange');
}
};
const updateNumericValues = _ => {
SETTINGS.minFS.obj.value = SETTINGS.minFS.value;
SETTINGS.maxFS.obj.value = SETTINGS.maxFS.value;
SETTINGS.minVW.obj.value = SETTINGS.minVW.value;
SETTINGS.maxVW.obj.value = SETTINGS.maxVW.value;
}
const convertNumericValues = _ => {
const prevUnit = SETTINGS.units.previousValue;
const unit = SETTINGS.units.value;
switch (unit) {
case 'px' :
switch (prevUnit) {
case 'em' :
case 'rem' :
// multiply by 16
SETTINGS.minFS.value = SETTINGS.minFS.value * 16;
SETTINGS.maxFS.value = SETTINGS.maxFS.value * 16;
SETTINGS.minVW.value = SETTINGS.minVW.value * 16;
SETTINGS.maxVW.value = SETTINGS.maxVW.value * 16;
updateNumericValues();
break;
}
break;
case 'em' :
case 'rem' :
switch (prevUnit) {
case 'px' :
// divide by 16
SETTINGS.minFS.value = SETTINGS.minFS.value / 16;
SETTINGS.maxFS.value = SETTINGS.maxFS.value / 16;
SETTINGS.minVW.value = SETTINGS.minVW.value / 16;
SETTINGS.maxVW.value = SETTINGS.maxVW.value / 16;
updateNumericValues();
break;
}
break;
}
}
const updateUnits = _ => {
let units = document.querySelectorAll('.units');
for (const unit of units) {
unit.textContent = SETTINGS.units.value;
}
}
/* Local Storage */
const useLocalStorage = (function () {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}());
const getStoragePropertyValue = prop => {
if (!useLocalStorage) return;
const store = JSON.parse(localStorage.getItem('FRPCalc'));
if (!store) return;
return store[prop];
};
const setStoragePropertyValues = _ => {
if (!useLocalStorage) return;
const store = {};
Object.keys(SETTINGS).forEach(function (prop) {
store[prop] = SETTINGS[prop].value + '';
});
localStorage.setItem('FRPCalc', JSON.stringify(store));
};
const updateOutput = _ => {
const resultCSS = document.getElementById('resultCSS');
if (!resultCSS) return;
// Simplify variables
const unit = SETTINGS.units.value;
const selector = SETTINGS.selector.value;
const property = SETTINGS.property.value;
const minFS = SETTINGS.minFS.value;
const maxFS = SETTINGS.maxFS.value;
const minVW = SETTINGS.minVW.value;
const maxVW = SETTINGS.maxVW.value;
const method = SETTINGS.methods.value;
// Booleans
const useClamp = !!(method === 'clamp');
const useMinmax = !!(method === 'minmax');
const useStops = !!(method === 'stops');
const useComments = !!SETTINGS.comments.obj.checked;
const useSafariFix = !!SETTINGS.safarifix.obj.checked;
const useLonghand = !!SETTINGS.longhand.obj.checked;
const strTab = (useMinmax || useClamp) ? '' : ' ';
const getMultiplier = _ => {
let multiplier = 100 * (maxFS - minFS);
// From default values
// m = 100 * (24 - 16)
// m = 100 * 8
// m = 800
multiplier /= (maxVW - minVW);
// m = m / (1920 - 768)
// m = 800 / 1152
// m = 0.69444444
// Force to 4 dec placed string
multiplier = Math.round(multiplier * 10000) / 10000 + '';
// m = "0.6944"
return multiplier;
};
const getSynopsisStr = _ => {
let str = '';
const addPx = unit !== 'px';
if (useComments) {
str += '/* ';
str += minFS + unit;
str += addPx ? `(${minFS * 16}px)` : '';
str += ` @ ${minVW + unit}`;
str += addPx ? `(${minVW * 16}px)` : '';
str += ' increasing to ';
str += maxFS + unit;
str += addPx ? `(${maxFS * 16}px)` : '';
str += ` @ ${maxVW + unit}`;
str += addPx ? `(${maxVW * 16}px)` : '';
str += ' */';
str += '\n';
}
return str;
};
const getQueryStr = _ => {
let str = '';
let query = unit;
if (query === 'rem') {
query = 'em';
if (useComments && !useMinmax && !useClamp) {
str += '/* Ems strongly recommended on media queries! */\n';
}
}
if (!useMinmax && !useClamp) {
str += `@media (min-width: ${minVW}${query}) {\n`;
}
return str;
};
const getMethodStr = _ => {
let str = '';
switch (method) {
case 'clamp':
str += ` ${property}: clamp(${minFS}${unit}, ${strCalc}, ${maxFS}${unit});\n`;
break;
case 'minmax':
str += ` ${property}: min(max(${minFS}${unit}, ${strCalc}), ${maxFS}${unit});\n`;
break;
default: // 'stops' || 'nostops'
str += ` ${strFS}\n`;
}
return str;
};
const getSafariFixStr = _ => {
let str = '';
if (useSafariFix) {
if (useComments) {
str += `\n${strTab} /* Safari resize fix */\n`;
}
str += `${strTab} min-height: 0vw;\n`;
}
return str;
};
const getStopQueryStr = _ => {
let str = '';
if (useStops) {
if (useComments) {
str += '/* Prevent scaling beyond this breakpoint */\n';
}
str += `@media (min-width: ${maxVW}${unit === 'rem' ? 'em' : unit}) {\n`;
str += ` ${selector} {\n`;
str += ` ${property}: ${maxFS}${unit};\n`;
str += ' }\n';
str += '}\n';
}
return str;
};
resetCopyBtn();
const multiplier = getMultiplier();
const baseSize = (unit === 'px') ? minFS / 16 : minFS;
let strCalc = `calc(${baseSize}rem + ((1vw - ${(minVW / 100) + unit}) * ${multiplier}))`;
if (useLonghand) {
strCalc = `calc(${baseSize}rem + (${maxFS} - ${minFS}) * ((100vw - ${minVW}${unit}) / (${maxVW} - ${minVW})))`;
}
const strFS = `${property}: ${strCalc};`;
// Store for popup window
OUTPUT.text = strFS;
// Build output as a string
let str = getSynopsisStr();
str += getQueryStr();
str += `${strTab}${selector} {\n`;
str += getMethodStr();
if (useComments) {
if (unit === 'px') {
str += `${strTab} /* Note: The calc base value (${baseSize}rem) MUST be stated in REM to maintain accessibility */\n`;
}
if (useLonghand) {
str += `${strTab} /* Where: calc = min_font_size_in_rem + (max_font_size - min_font_size) * ((100vw - min_viewport_including_${unit}_unit) / (max_viewport - min_viewport)) */\n`;
} else {
str += `${strTab} /* Where: ${multiplier} = 100 * ${property}_difference / viewport_width_difference */\n`;
}
}
str += getSafariFixStr();
str += `${strTab}}\n`;
if (!useMinmax && !useClamp) {
str += '}\n';
}
str += getStopQueryStr();
// Local storage
setStoragePropertyValues();
// Store for popup window
OUTPUT.value = str.replace(selector, ':root');
resultCSS.textContent = str;
// External module for syntax highlighting
if (typeof Prism === 'object') {
Prism.highlightElement(resultCSS);
}
}
// Open settings and for each primary run initialise and set the values
const initialise = _ => {
// Default values have to be set prior to initialisation
Object.keys(SETTINGS).forEach(function (prop) {
const value = getStoragePropertyValue(prop) || SETTINGS[prop].value;
SETTINGS[prop].value = value;
});
Object.keys(SETTINGS).forEach(function (prop) {
SETTINGS[prop].init();
SETTINGS[prop].set(SETTINGS[prop].value);
});
}
initialise();
updateUnits();
return {
SETTINGS : SETTINGS,
OUTPUT : OUTPUT
}
})();
Also see: Tab Triggers