CSS Variables - Detailed Overview

Introduction to CSS Variables

CSS Variables, also known as custom properties, allow you to store values that you can reuse throughout your CSS. They are defined using the -- prefix and can be used to make your CSS more maintainable and easier to update.

Basic Example

Here’s an example of defining and using a CSS variable:

Default Box

CSS Code:


/* Define CSS Variables */
:root {
    --main-bg-color: lightblue;
    --text-color: darkblue;
}

/* Use CSS Variables */
.box {
    background-color: var(--main-bg-color);
    color: var(--text-color);
}
                

Advanced Example

In this example, we'll use CSS variables to control the size of elements dynamically:

Large Box

CSS Code:


/* Define CSS Variables */
:root {
    --main-bg-color: lightgreen;
    --text-color: darkgreen;
}

/* Use CSS Variables */
.box {
    background-color: var(--main-bg-color);
    color: var(--text-color);
}

.box-large {
    width: 200px;
    height: 200px;
}