Wrong about CSS Variable fallbacks


by Jeremy Caudle
code

I was doing it all wrong and thought the default you can provide when using CSS variables served as a fallback for older browsers. I'm glad I discovered the right way to do it, and boy do I feel silly for now realizing it earlier.

I was doing fallbacks for CSS variables incorrectly!

After working through a workshop on CSS Variables on Treehouse, I realized I was not doing fallbacks for CSS variables correctly. So I thought today I'd do some repitition to ensure that I get it stuck in my head.

When you want to provide a fallback for a property using a variable as its value, provide an declaration of the property using that variable's value directly above it. Add color: #ff0099; on the line above color: var(--var-name, #ff0099); for example. The cascade takes care of overwriting it for browsers that support CSS variables.

View the code:

HTML and JS
<section class="code-block">
            <h2>I was doing fallbacks for CSS variables incorrectly!</h2>
            <p>After working through a workshop on CSS Variables on <a href="https://teamtreehouse.com">Treehouse</a>, I realized I was not doing fallbacks for CSS variables correctly. So I thought today I'd do some repitition to ensure that I get it stuck in my head.</p>
            <p>When you want to provide a fallback for a property using a variable as its value, provide an declaration of the property using that variable's value directly above it. Add <code>color: #ff0099;</code> on the line above <code>color: var(--var-name, #ff0099);</code> for example. The cascade takes care of overwriting it for browsers that support CSS variables.</p>
        </section>
CSS
/* Variables */
            :root {
                --max-wrapper: clamp(16em, 90vw, 60em);
                --main-bg: rgba(0,0,0,.1);
                --make-it-tall: 60vh;
                --focus-element: 3rem auto;
            }
						
section.code-block {
                max-width: 60em;
                max-width: var(--max-wrapper, clamp(16em, 90vw, 60em));
                background-color: rgba(0, 0, 0, .1);
                background-color: var(--main-bg, rgba(0,0,0,.25));
                min-height: 60vh;
                min-height: var(--make-it-tall, 60vh);
                margin: 3rem auto;
                margin: var(--focus-element, 3rem auto);
                padding: 1rem;
            }

            section.code-block h2 {
                text-align: center;
                font-family: Helvetica, Arial, sans-serif;
            }

            section.code-block p {
                max-width: 60ch;
                margin-left: auto;
                margin-right: auto;
                line-height: 1.5;
            }

            section.code-block code {
                margin: 0;
                padding: .125rem .25rem;
                background-color: rgba(0, 0, 0, .3);
                color: #dedede;
            }