Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding repeated constants in 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)?

like image 478
Matt Sheppard Avatar asked Aug 27 '08 13:08

Matt Sheppard


People also ask

How do you avoid duplicating colors or fonts in CSS?

You can use global variables to avoid duplicacy. Here, you can initialize a global variable in :root pseudo class selector. :root is top level of the DOM. However, you can always use the Syntactically Awesome Style Sheets i.e. In case Sass, you have to use $variable_name at the top to initialize the global variable.

Can you use constants in CSS?

CSS constants don't exist in a spec, they're currently just variables that aren't re-assigned. Whether CSS is a programming language or not, it results in a different environment for variables to live, compared to something like Javascript.


1 Answers

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; 
}
like image 124
John Slegers Avatar answered Sep 30 '22 15:09

John Slegers