DEV Community

Cover image for Swap out text colors with Css Custom properties
Stephan Nijman
Stephan Nijman

Posted on • Edited on • Originally published at since1979.dev

Swap out text colors with Css Custom properties

Change all text colors inside a specific section of a webpage.

In this video we will take a look at how we can set up our css custom properties/variables so that we can use them to swap out all text colors in a specific section of our webpage.

Below is a completed code example.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Using css variables to change color in a specific section</title>
    <link rel="stylesheet" href="./styles.css">
</head>
<body>

    <section>
        <h2>Lorem ipsum dolor sit amet.</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A adipisci aperiam asperiores assumenda at atque cupiditate debitis dolores eligendi enim, error esse et excepturi exercitationem facilis fugit ipsam laboriosam magni necessitatibus nulla obcaecati odio porro sint sunt suscipit vel voluptatum.</p>
    </section>

    <!-- This section should have a dark background, so we add a .dark class -->
    <section class="dark">
        <h2>Esse nobis obcaecati possimus totam.</h2>
        <p>Cupiditate delectus deleniti dolorem doloribus explicabo facere incidunt maiores molestias, nemo nisi nobis quasi quis reiciendis repellat sed ut veritatis vitae voluptatum! Animi illo quos rerum temporibus. Distinctio ea fuga iusto mollitia officia! Error explicabo hic minima quos sit tenetur.</p>
    </section>

    <section>
        <h2>Aperiam expedita itaque non quasi.</h2>
        <p>Iste molestias mollitia possimus. Ad consequatur consequuntur enim ipsum iusto magni nemo, nostrum officia perferendis quaerat quo quod repellat reprehenderit saepe sapiente, sunt tempore tenetur vel velit veniam? Deleniti doloribus illum in minus modi nemo perferendis placeat quasi sapiente tenetur!</p>
    </section>

    <style>
        /* Custom property for text colors */
        :root {
            --txt-clr: #333333;
        }

        /* Set global text colors */
        h2 {
            color: var(--txt-clr);
        }
        p {
            color: var(--txt-clr);
        }

        .dark {
            /* Set a background color for the .dark section  */
            background-color: #333333;
            /* Redeclare text color insidde teh .dark section */
            --txt-clr: #efefef;
        }
    </style>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Subscribe and Follow

Subscribe to my Youtube channel.

Follow me on Twitter

Thanks for reading/watching and stay safe

Top comments (0)