Reduce repetition in CSS styles

CSS variables allow you to define style values in a central location. They provide an easy way to have consistent styles in your documents. There is no need to enter specific values for elements with a similar design, simply refer to the variable. Updating the variable updates the appearance of the respective elements, which greatly simplifies maintenance.

Just like variables in a programming language they need to be defined before you can use them. This is best done in the :root pseudo class. This makes the variables globally scoped so they are available to the whole stylesheet file and can even be used in other stylesheets.

CSS variable names start with double hyphens/dashes and cannot not use spaces or other special characters.

:root {
    --primary-color: #2564DB;
    --contrast-color: #EFEFEF;
    --radius: 5px;
}

To use a variable in you CSS simply put the name (including the two dashes) in the var(); function.

h1, h2, h3 {
    color: var( --primary-color );
    margin-bottom: 0.2rem;
}

p b {
    color: var( --primary-color );
}

.box {
    background-color: var( --primary-color );
    color: var( --contrast-color );
    border-radius: var( --radius );
    padding: 5mm;
}

.icon-box {
    background-color: var( --primary-color );
    color: var( --contrast-color );
    border-radius: var( --radius );
    display: flex;
    align-items: center;
    justify-content: center;
}

The following shows these CSS rules in action: