All Marked Up

A tasty brew of web standards and internet culture.

Posts tagged with “CSS”

On variables and mixins in CSS

So in a previous post I talked briefly about my ‘wishlist’ for CSS3 (or beyond) – additions to the language that I would really like to see implemented in order to give us a better, more flexible way of tackling  a wide variety of issues.

Out of the five things I mentioned – Basic math, delegation, positioning model tweaks, constants, mixins – the last two are perhaps the most straightforward. Whilst in the post I talked about better tools for problem solving, variables and mixins are really more about being able to write cleaner, more maintainable and flexible CSS code with a better separation from the associated HTML.

I’m going to go into a little more detail on what I actually mean when I talk about variables and mixins in CSS, how they could help us write better code, and why they haven’t yet been (and may never be) implemented.

Constant Variables

Before I start talking about variables in CSS, a quick word on terminology: I use the term ‘variables’ here because it has gained some popularity, but it would really be more correct to describe them as ‘constants’; their value, once assigned, is not expected to be mutable over the course of the document.

So, the basic concept is that you would be able to define a variable that holds a value (such as a hex colour, or a width) and then be able to use the name of that variable to refer to it later on in the stylesheet. So you could do something like this:

@variables {
    myCompanyBrandingColour: #F00;
    myCompanyFonts: 'Comic Sans', Arial, sans-serif;
}
 
#header {
    background-color: var(myCompanyBrandingColour);
}
 
p {
    font-family: var(myCompanyFonts);
{

That way, when your company rebrands, to change the branding colours and fonts throughout the site you would be able to update the value of just one or two variables, rather than having to trawl through your stylesheets looking for instances of that colour or font-family.

Sounds good doesn’t it? This idea is certainly not new, and has cropped up repeatedly in one form or another over the last ten years or so. A few members of the W3C have even written a detailed spec for it, and it was even implemented in Webkit nightlies for a while (it was removed because it’s implementation in Safari would have been “hugely popular“, but they didn’t feel confident enough that the spec wouldn’t change in the future and thus leave them having to support an outdated implementation).

Yet this concept keeps on getting repeatedly shot down on mailing lists and influential people in the W3C such as Bert Bos (one of the original formulators of CSS, nonetheless) have written at length about why this idea will not get included in the spec anytime soon, if ever.

This is a real shame, in my opinion. There is a clear demand for this feature in CSS, and the arguments made against it just don’t work for me. Some of Bert Bos’ arguments in the aforelinked essay seem almost laughable:

“…it is quite likely that somebody who is trying to learn CSS will give up learning it when he sees that style sheets that occur on the Web don’t actually look like the tutorials he started from.”

…which sounds like an argument against progress in any web development language (or in any other programming language at all for that matter!) and is clearly nonsense – what about all the new additions to CSS to be implemented as part of the CSS3 spec, for instance?

He also talks about the ‘implementation effort’ of including variables/constants in CSS. This is another argument that I have no time for – I just don’t think that (within reasonable limits) the W3C should be concerned with how difficult features are to implement. The Webkit nightlies implementation has already shown that this is achievable, and if this was to be included as part of the official CSS spec then I have no doubt that browsers manufacturers would scramble to implement it, effort required or not.

The only serious issue with this idea, in my mind, is backwards-compatibility. Older browsers that didn’t support this feature would ignore rules specified in this way, so there would need to be some way of providing a fallback. I’m confident an acceptable solution can be found to this; and in the meantime at least if there was a officially supported spec then the gap could be temporarily filled with ’standards compliant’ CSS pre-processors, rather than having the mishmash of non-compatible CSS pre-processor implementations that we have today.

Mixin it up

So, on to mixins. A mixin is an author-defined rule-set that can be ‘mixed-in’ to other sets of rules for particular selectors. The LESS CSS pre-processor implementation of mixins looks like this (from their documentation):

.bordered {
    border-top: dotted 1px black;
    border-bottom: solid 2px black;
}
 
.post a {
    color: red;
    .bordered;
}

What is happening here? Well firstly, we are defining a rule-set with a class selector of ‘bordered’ in the usual fashion. Then, in the .post a rule-set you can see that the class name has been used inside the braces – indicating that the rules defined in the .bordered class are to be imported into the .post a rules at that point.

It’s possible to do something very similar to this today; in fact I use it all the time – I split my rule-sets up into discrete chunks using class names, and then apply those one or more of those classes in the HTML markup to achieve the desired result. However, this has one big problem associated with it: it breaks the paradigm of the separation of style and content, and ties our markup and styles together in a way that wouldn’t be necessary if we could use mixins in our CSS.

Again, there are many people both for and against the ideas of mixins being added to the CSS spec. In fact, Bert Bos’s arguments in his article could probably be equally applied to mixins. However the advantages of having the ability to be able to define class-based style rules and then have them available to use as part of compound rule-sets seem obvious to me; helping us stick closer to DRY principles, reducing maintenance, helping to ensure consistency within sites, and removing a common dependence on markup would all be good things, would they not?

In summary

What I would like to see is a way to cut down on the amount of CSS I write, and make it more portable, more flexible and more maintainable. I think that variables and mixins in CSS would help that become an achievable goal. There are many others who feel similarly; I just wish that it didn’t seem like the W3C had completely closed out the subject of additions such as these to the CSS language.

A quick footnote on CSS pre-processors:

I have mentioned ‘CSS pre-processing’ various times above; basically this refers to the server-side parsing of CSS code before it is output to the browser (cached, hopefully!). This is a way that some of these features can be used today – the rules are included in the stylesheet, they are converted to ‘normal’ CSS by the pre-processor, and then the browser can parse the stylesheet as per usual.

Pre-processing has been recommended by various members of the W3C and others as the preferred way to use features like these without them having to be added to the spec. Which is fine, except many people don’t want to use a server-side technology to do this, or can’t, for technical or access reasons. And another problem with them is that they are not working to any particular spec – all the implementations vary greatly, so your CSS code instantly becomes non-portable and your knowledge non-transferable.

No Comments »

CSS3 and beyond

I have spent quite a while recently tinkering about with the parts of the CSS3 spec that have been already implemented in various browsers (albeit mostly via vendor-prefixed properties) – things like border-radius, rgba colours, box-shadow, media queries and more. Useful additions to our toolbox, and ones which will undoubtedly cut down on the amount of general hackery we need to use to do relatively simple things; a good thing, in other words.

But there are parts of the spec that are, in my mind, definitely not a good thing. Things like the ascii-art nightmare that is the so-called ‘Advanced/Template Layout Module‘ for example, make me go weak at the knees. Why is something this offensive even being considered when one or two minor additions to the positioning model we already have would allow us to intuitively create layouts without totally re-inventing the wheel?

Parts of the spec such as this make me seriously concerned that the CSS WG are focussed on serving up high-level, situation specific solutions to problems rather than thinking about how they could evolve CSS to provide better low-level tools that would allow us to tackle problems on a more generic level. It’s a case of “give a man a fish and he’ll have food for a day, teach a man to fish and he’ll have food for life”. Give us a complex layout solution like the one proposed and you solve (in a horrible way) one problem; give us the ability to do basic maths and a few fixes to the current positioning system and we’ll be able to use them to solve all sorts of issues, not just generic page layouts.

So what would I like to see added to the CSS3 (or maybe CSS4!) spec? Glad you asked. The list below is a few things I would like to see added, that I think would aid CSS developers in their everyday work. Note there are no solutions to specific problems here; what I want is the tools to be able to sensibly solve both problems I encounter today and problems I haven’t encountered yet and can’t yet imagine.

  • Basic math – I want to be able to do things like width: 100%-200px; in my stylesheets.
  • Delegation – Give me a mechanism so that I can define an element’s style by way of reference to another element’s properties.
  • Positioning tweaks – let me have a property that allows the element it’s applied to to clear it’s absolutely positioned siblings, in a similar way that clear:both; does for floated elements.
  • Constants (or variables, if you prefer) – let me define constants for re-use to make my code clearer and more maintainable.
  • Mixins – Let me define reusable groups of CSS properties that I can ‘mix in’ to the properties of other selectors without having to add multiple class names to my HTML.

People’s knee-jerk reaction to any of these suggestions is generally “CSS isn’t a programming language and it shouldn’t be made to behave like one!!”. Well, I’m sorry, but for me that argument just doesn’t stand up. CSS is a tool, and I believe that tools should be honed to better do the jobs that are asked of them. CSS wasn’t intended to be a layout solution in the first place, but we have hacked it into becoming that. People think that adding in ideas like the above make CSS more complex; I would personally argue that they would make it less complex; abstractions such as mixins and constants, and tools like basic maths should make it much more obvious what the authors intentions were when penning a certain rule or property.

Over the next couple of weeks I hope to go into a little more detail on each of the points on my ‘wish list’ above and illustrate how I think they could work and their potential application to specific, common situations. But for now, let me just point out that none of the things I have talked about are particularly new ideas; Google any one of them and you will find many people with the same viewpoint as I, and plenty more food-for-thought to boot.

4 Comments »

SpriteMe. Fiendishly clever little bookmarklet by Steve Souders (of ‘Even Faster Websites’ fame) that will automagicaly assess all the background images in a page, calculate which could be sprited together and then generate those sprites and the corresponding CSS for you. Quite astounding. (Via Matthew Buchanan)

iTunes + CSS3. Judson Collier has a peek under the hood of the iTunes store to check out the stylesheets. Definitely worth downloading the CSS for a poke around, although I take issue with his assertion that “…web design innovation only really occurs when your entire user base uses the same browser”.

Bulletproof @font-face implementation. Paul Irish has figured out a pretty solid-looking @font-face implementation that covers checking for local copies of the font and providing IE with it’s .eot version whilst keeping server resources to a minimum.

Font Squirrel’s @font-face kits. I’ve used the Font Squirrel site several times before but somehow have only just seen the @font-face kits they offer ready for download. They come complete with stylesheet and EOT versions for IE – very handy.