Css – Avoiding repeated constants in CSS

css

Are there any useful techniques for reducing the repetition of constants in a CSS file?

(For example, a bunch of different selectors which should all apply the same colour, or the same font size)?

Best Solution

Recently, variables have been added to the official CSS specs.

Variables allow you to so something like this :

body, html {
    margin: 0;
    height: 100%;
}

.theme-default {
    --page-background-color: #cec;
    --page-color: #333;
    --button-border-width: 1px;
    --button-border-color: #333;
    --button-background-color: #f55;
    --button-color: #fff;
    --gutter-width: 1em;
    float: left;
    height: 100%;
    width: 100%;
    background-color: var(--page-background-color);
    color: var(--page-color);
}

button {
    background-color: var(--button-background-color);
    color: var(--button-color);
    border-color: var(--button-border-color);
    border-width: var(--button-border-width);
}

.pad-box {
    padding: var(--gutter-width);
}
<div class="theme-default">
    <div class="pad-box">
        <p>
            This is a test
        </p>
        <button>
           Themed button
        </button>
    </div>
</div>

Unfortunately, browser support is still very poor. According to CanIUse, the only browsers that support this feature today (march 9th, 2016), are Firefox 43+, Chrome 49+, Safari 9.1+ and iOS Safari 9.3+ :

enter image description here


Alternatives :

Until CSS variables are widely supported, you could consider using a CSS pre-processor language like Less or Sass.

CSS pre-processors wouldn't just allow you to use variables, but pretty much allow you to do anything you can do with a programming language.

For example, in Sass, you could create a function like this :

@function exponent($base, $exponent) {
    $value: $base;
    @if $exponent > 1 {
        @for $i from 2 through $exponent {
            $value: $value * $base;
        }
    }
    @if $exponent < 1 {
        @for $i from 0 through -$exponent {
            $value: $value / $base;
        }
    }
    @return $value; 
}