123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

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.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div id="preview">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
</div>
<main id="main">
  <div id="bg_group" class="group">
    <label for="bg_color">Background Color <input type="text" id="bg_color" value="rgb(0, 0, 0)" onclick="this.select()">
				</label>
  </div>
  <div id="font_group" class="group">
    <label for="font_color">Font Color <input type="text" id="font_color" value="rgb(18, 136, 177)" onclick="this.select()">
				</label>
  </div>
  <div id="wcag" class="group">
    <p class="test">AA: <span id="passAA" class="pass">[PASS]</span><span id="failAA" class="fail">[FAIL]</span></p>
    <p class="test">AAA: <span id="passAAA" class="pass">[PASS]</span><span id="failAAA" class="fail">[FAIL]</span></p>
    <p id="ratio" class="test">21</p>
  </div>
</main>
            
          
!
            
              :root {
    --main_bg: hsl(210, 66%, 3%);
}

* {
    box-sizing: border-box;
}

body {
    font-size: 16px;
    background: var(--main_bg);
}

#preview {
    display: grid;
    margin: 20px 6% 40px 6%;
    grid-auto-rows: minmax(100px, auto);
    grid-template-columns: repeat(1, 3fr);
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.40), 0 6px 20px 0 rgba(0, 0, 0, 0.40);
}

#preview p {
    padding: 20px;
    font-size: 1.1rem;
    text-align: center;
}

main {
    display: grid;
    grid-auto-rows: minmax(100px, auto);
    grid-gap: 30px;
    margin: 0px 6%;
}

.group {
    --size: 320px;
    width: var(--size);
    height: var(--size);
    padding-top: 20px;
    display: block;
    text-align: center;
    border-radius: 5px;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.70), 0 6px 20px 0 rgba(0, 0, 0, 0.70);
    font-size: 2rem;
}

label {
    font-size: 1rem;
    margin: 20px;
}

input {
    font-size: 1.6rem;
    border-radius: 5px;
    color: #444;
}

input[type="text"] {
    --size: 290px;
    --margins: calc((320px - var(--size))/2);
    margin: var(--margins);
    width: var(--size);
    text-align: center;
}

#ratio {
    font-size: 1.5rem;
}

.test {
    color: #ddd;
}

.pass {
    color: forestgreen;
}

.fail {
    color: firebrick;
}

@media screen and (min-width: 820px) {
    main {
        grid-template-columns: repeat(2, 1fr);
    }
    #preview p {
        font-size: 1.2rem;
    }
}

@media screen and (min-width: 1200px) {
    main {
        grid-template-columns: repeat(3, 1fr);
    }
    #preview p {
        font-size: 1.5rem;
    }
}
            
          
!
            
              const main = document.getElementById('main');
const preview = document.getElementById('preview');
const txt = preview.querySelector('p');

// 
const bg_group = document.getElementById('bg_group');
const bg_group_lbls = bg_group.querySelectorAll('label');
const bg_color = document.getElementById('bg_color');

// 
const font_group = document.getElementById('font_group');
const font_group_lbls = font_group.querySelectorAll('label');
const font_color = document.getElementById('font_color');


// wcag group
const passAA = document.getElementById('passAA');
const failAA = document.getElementById('failAA');
const passAAA = document.getElementById('passAAA');
const failAAA = document.getElementById('failAAA');
const ratio = document.getElementById('ratio');


// ------------------------------------------------------- RANDOM COLORS ON START

const randNum0 = (N) => Math.floor(Math.random() * (N)); // increase passing results
const randNum1 = () => Math.floor(Math.random() * (116)) + 140; // increase passing results

// decrease the number of dark brown results
const randColor0 = () => `rgb(${randNum0(36)}, ${randNum0(16)}, ${randNum0(76)})`;
const randColor1 = () => `rgb(${randNum1()}, ${randNum1()}, ${randNum1()})`;

// ------------------------------------------------------------------------------


// auto contrast labels
function ccRGB(rgb) {
    let [r, g, b] = rgb.match(/\d+/g);
    [r, g, b] = [r * 0.2126, g * 0.7152, b * 0.0722];
    return (r + g + b) >= 128 ? "black" : "white";
}

// update all bg_group components
const setBgColors = (c) => {
    bg_color.value = c;
    bg_group.style.background = c;
    preview.style.background = c;
    bg_group_lbls.forEach(lbl => {
        lbl.style.color = ccRGB(c);
    });
}
setBgColors(randColor0());


// update all font_group components
const setFontColors = (c) => {
    font_color.value = c;
    font_group.style.background = c;
    txt.style.color = c;
    font_group_lbls.forEach(lbl => {
        lbl.style.color = ccRGB(c);
    });
}
setFontColors(randColor1());

const getsRGB = (v) => (v <= 0.03928) ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;

const LUM = (color) => {
    let [r, g, b] = color.match(/\d+/g);
    r = getsRGB(r / 255) * 0.2126;
    g = getsRGB(g / 255) * 0.7152;
    b = getsRGB(b / 255) * 0.0722;
    return r + g + b;
}

// "Contrast" was a term associated with fine art late 17th century, in the sense "juxtapose so as to bring out differences in form and color". (Etymology) Latin "contra-" against + "stare" stand.

const getContrast = (colorA, colorB) => {
    const L1 = (typeof colorA === 'string') ? LUM(colorA) : colorA;
    const L2 = (typeof colorB === 'string') ? LUM(colorB) : colorB;
    const compare = (Math.max(L1, L2) + 0.05) / (Math.min(L1, L2) + 0.05);
    // truncate to two decimal places without rounding
    const contrast = compare.toString().match(/(?:\d*([.])\d{2})/);
		// 	"x == undefined also checks whether x is null" 
    if (contrast != undefined) return contrast[0];
    return (L1 === L2) ? 1 : 21;
}

// ------------------------------------------------------- ADDS HEX SUPPORT 

const isHEX = /(^#?[0-9A-F]{6}$)|(^#?[0-9A-F]{3}$)/i;

const convertHEX = (color) => {
    if (color.length < 6) {
        let [r, g, b] = color.match(/[0-9A-F]/ig);
        color = `${[r, r, g, g, b, b].join('')}`;
    }
    color = `0x${color.replace("#", '')}`;
    let [rr, gg, bb] = [color >> 16, color >> 8, color];
    [rr, gg, bb] = [rr & 255, gg & 255, bb & 255];
    return `rgb(${rr}, ${gg}, ${bb})`;
}

const getValue = (el) => {
    const inputValue = el.value;
    return (isHEX.test(inputValue)) ? convertHEX(inputValue) : inputValue;
}

// ------------------------------------------------------------------------
const para = document.querySelector("#preview p");
const compStyles = window.getComputedStyle(para);
const getFontSize = () => compStyles.getPropertyValue("font-size");

function result() {
  const fsize = Number(getFontSize().replace("px", ''));
  const [ratioAA, ratioAAA] = (fsize > 24) ? [3, 4.5] : [4.5, 7];

  const testAA = (val) => (Number(val) > ratioAA) ? "PASS" : "FAIL";
  const testAAA = (val) => (Number(val) > ratioAAA) ? "PASS" : "FAIL";

    const colorOne = getValue(bg_color);
    const colorTwo = getValue(font_color);
    const contrastValue = getContrast(colorOne, colorTwo);

    return {
        colors: [colorOne, colorTwo],
        contrast: contrastValue,
        testAA: testAA(contrastValue),
        testAAA: testAAA(contrastValue)
    };
}

// ------------------------------------------------------------------------

function submit() {

    const setAA = (grade) => {
        if (grade === "PASS") {
            if (passAA.hasAttribute('hidden'))
                passAA.removeAttribute('hidden');
            failAA.setAttribute("hidden", "true");
        } else {
            passAA.setAttribute("hidden", "true");
            if (failAA.hasAttribute('hidden'))
                failAA.removeAttribute('hidden');
        }
    }

    const setAAA = (grade) => {
        if (grade === "PASS") {
            if (passAAA.hasAttribute('hidden'))
                passAAA.removeAttribute('hidden');
            failAAA.setAttribute("hidden", "true");
        } else {
            passAAA.setAttribute("hidden", "true");
            if (failAAA.hasAttribute('hidden'))
                failAAA.removeAttribute('hidden');
        }
    }

    const setRatio = (value) => {
        ratio.textContent = `Ratio: ${value}`;
    }

    const answer = result();
    setAA(answer.testAA);
    setAAA(answer.testAAA);
    setRatio(answer.contrast);
    setBgColors(answer.colors[0]);
    setFontColors(answer.colors[1]);
}

submit();

bg_color.addEventListener('change', submit);
font_color.addEventListener('change', submit);


//
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console