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)?
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.
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.
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+ :
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With