CSS Variables, Yet Another Step in the Wrong Direction

From the first time I learned about CSS variables some time ago, I noticed it was a stupid implementation. This is what we get when the people writing the specifications are not one bit close to the real world development scene. How can a person who doesn’t write CSS on a daily basis know what the best way to implement something is. Add to that the fact that variables in CSS are completely useless by nature. However, the “developers” asked for them, and they got them.

CSS variables are still something that lives in the future. They are like an incredibly stupid monster that lives in another dimension, but that has managed to open a portal, and is now showing one of its ugly paws through it. But I’m not the type to mix science fiction with reality, and I don’t usually write in this style, so I’m going to stop now.

Going back to my usual ranting style, let me tell you why CSS variables are stupid, and dangerous. But first, lets take a look at the motivation.

I Want to Feel Like a Big Pants Geek Boy
Or Why CSS Variables

It is my belief that CSS variables come deep from the need of designers to feel like developers. I’m not trying to insult designers here. I have great respect for some of the work that great designers have done, but now that the web has given birth to the front-end wave, there are a lot of designers out there who want to feel like they can call themselves front-end engineers. This is not a good thing. Designers should be proud of being designers simply because their work is amazing. But being geek, nerd, and coder is the fashion now, so many designers want to be that too.

Today I read this on a blog post:

If there is one thing a language needs to qualify as a programming language, it’s variables; they’re incredibly useful, save us a bunch of work and typing, and improve coding all-round.

This is simply a demonstration of both, the need of some designers to feel like they can program, and their lack of knowledge of programming languages. But I’m not going to start attacking people just to make me feel better. I think I should just continue attacking CSS because after all, that is what is ultimately wrong. If we really want to make CSS better, we need to throw the current specs out the window, and start anew.

The Nightmare of CSS Variables

I wanted to have a bit of a better base for my arguments, so I decided to head to the source of the problem. I searched for the W3C specification of CSS variables. It is still an Editor’s Draft, but in this stage we can begin to see some of what is wrong with CSS variables. Take a look at this example, taken from the W3C site:


:root { var-color: blue; }
div { var-color: green; }
#alert { var-color: red; }
* { color: var(color); }

<p>I inherited blue from the root element!</p>
<div>I got green set directly on me!</div>
<div id='alert'>
  While I got red set directly on me!
  <p>I’m red too, because of inheritance!</p>
</div>

I really hope you see what is wrong there, but if you don’t, I’ll give you a hint: the paragraph element can be a different color depending on where it is, event though you specify a “specific” color for all elements. This is because of the stupid implementation of scope.

The scope of the variable is resolved in terms of the location of the element in the HTML structure. What!? This is wrong, and you can go and find as many justifications for this as you want, but it won’t change the fact that this is just wrong. It would have been better to implement namespaces rather than this kind of scope.

This behavior is defined as “cascading variables”. In a sense, it is not even a scope chain. It is a freaking cascade! Why would you want your variable values to cascade? This should be called randoms instead of variables, because the value of the variables will change almost randomly depending on where the element is in the html.

This cascading behavior introduces inconsistency. Inconsistency is enemy of robustness because it creates unexpected behavior. However, CSS variables introduce a whole lot of inconsistency and complexity to an already complex language. The bad thing about this complexity is that the complexity is not in the language itself, but in the way the language has to be written in order to be efficient. In other words, writing complex, hard-to-maintain, CSS is a requirement so much they almost advertise it as a feature.

Who Needs Variables Anyway?

I like to believe there is a better way to write CSS. I’ve been recently experimenting with what I call Subscription Based CSS. It has allowed me to create more consistent behavior, easier-to-maintain CSS, and a smaller code base. Explaining Subscription Based CSS is out of the scope of this entry, but the basic idea is to develop sets of styles, and simply add selectors to them. This eliminates completely the need for variables. Think of this example:


{
color: #bada55;
}

We have defined a color set. Now, whenever you need a certain element to have that text color, you simply add a selector to the rule set. For example, if you want all your h1 elements to have this color, you simply subscribe them:


h1 {
color: #bada55;
}

If you also want elements with the class “badass” to have this color, you subscribe that selector too:


.badass,
h1 {
color: #bada55;
}

There is no need for a variable called var-badass, and there is no unexpected behavior. The .badass elements, and the h1 elements will always have the same color regarding of cascade values.

You can apply this same principle to any CSS property, and you can do more than variable can do. For example, if you want elements to have the badass background color, and white font color for nice contrast, you define that set:


.badass,
h1 {
background-color: #bada55;
color: #fff;
}

This is a much better way to deal with constant values.

F! Semantics

In my early days, I was pro-semantics. Semantics were the hype back then, and I saw a lot of value in that. Semantics rely heavily in class names, and we learned that using class names that described the visual representation of the element was bad. This means that if you have a class like “centered_text” you are doing it wrong. Why? For the sake of semantics, of course.

Nowadays I’m not as big a fan of semantics as I used to be. Class-based semantics are a redundant task that has little added benefit for the end user. They are of great benefit for robots, and automated machines, but we do web for users, not robots. Once you forget semantics, writing subscription based css is really easy.

I don’t think CSS variables will go away. They are just another feature in the web that takes us a bit further from where we should be, and that diverges us a bit more from the direction we should be following, but like everything else, it is up to the developer to use the feature or not. I’m sure they will be loved by many because we tend to see any new feature like a new toy we must use as much as possible. I think we will start seeing CSS frameworks that claim to be the perfect solution for CSS variables, just like it happened with grids. With that in mind, I can safely say that I saw the future, and it was awful.

grumpy cat

I Love My Work, but I Hate Web Development

The more I work on web development, the more I realise how much I hate it. This is a very strange situation, especially because I do really love my work; I just hate the way I have to do it.

Let me explain what I mean. I hope that by the end of this long read you get the idea that I’m setting to communicate here, and that you join me on my rebellion against web development as it is today.

I will start with an example. Imagine a world where there are no computers, or typewriters, or even paper. All you have is rock and hard tools to scribe your thoughts. In this world there is a very high demand for books, which are made out of stone and cannot be mass-produced easily. You are a fiction writer. People love your books, and you love writing them. Except, that you hate having to write them.

It is not the idea of creating content that you hate, or the motion of writing itself, but rather the fact that it takes you a very long time to put those books on stone because of the rudimentary tools that you have. This is precisely what I mean in the title.

It is not the idea of creating an awesome website or webapp that I hate, but rather the nuisance that it represents actually creating them with the set of rudimentary technology that we have available. Even more annoying is the fact that not only do we have to use a very basic set of tools, but we also need to support even more archaic tools. And to add insult to injury, we are supposed to obey by a set of rules that have been laid out by people who mostly do not understand the web of today. Let along that one of tomorrow, which we should have gotten yesterday.

The more I work on web, the more I realise how wrong it feels to do it. It really feels wrong to have to create my content using a limited set of tags that were thought of by people who knew nothing about what I’m trying to create, and who would probably never care. It feels wrong to have to use an API that is mostly redundant (DOM), and designed by people whose work is not to create with this API. It feels wrong to have to do the same thing more than once to make sure that it works across browsers and platforms. I’m sure that by now you are getting the idea.

This is why Ajax libraries have succeeded. Ajax libraries are created, maintained, pushed, shaped, and refined by content creators, not by specification-and-standards writers. The people behind jQuery, Dojo, MooTools, YUI, and many others, are people who have created these tools to solve problems they have encountered in their journey as web and application developers. We need more of this, and less of W3C nonsense.

I used to be standards oriented until I discovered that the people behind the standards have no idea of what they are doing. Don’t get me wrong here. I have a lot of respect for the people who set out to standardise a huge mess such as the web. It is just that they have spent too much time trying that they haven’t realised the web changed.

The best time machine mankind has invented is called webstandards. While reading some of them, and not only web standards, one can feel like it’s re-living 2000 all over again. And it’s scary because sometimes you are actually reading a year-2000 document. This is insane. You cannot standardise the web of today when your base for standards is the web of 2000.

There are many examples of things that should have been done differently. One of the most common case-scenarios that frustrates me is CSS. In my opinion, and I express it because this is a very subjective essay, CSS is wrong. It starts with classes, then it degrades with some aspects of selectors, especially how they are interpreted, and it hits the bottom with the syntax passing for some other stages in the process.

The idea of classes is a language that has no way of extending this classes is wrong. One can argue that you can extend a class by adding the class name that you want to extend to the CSS declaration of the object from which you want to extend, like this:

.car{
color: blue;
width: 200px;
height: 50px;
}

If we want to create a new element that has the class name of truck, and we want it to extend the CSS of car, we can do it like this:

.car, .truck{
color: blue;
width: 200px;
height: 50px;
}
.truck{
width: 300px;
}

This is fairly simple, but not quite usable when working on real projects because most of the time, by the moment you reach truck, you already added a hundred lines under the .car declaration. You have two options. One is to move your .truck declaration 100 lines up and mess up your CSS file organisation. The other is to leave them both 100 lines apart from each other which is also not good because the it becomes a maintenance problem, which by the way the first option does too.

Moreover, this is not extending, it is merely subscribing two classes to the same set of rules. Subscriptions are good, but not as the base for extending classes.

How I think it should be done:

.car{
color: blue;
width: 200px;
height: 50px;
}
/*100 lines of code go here.*/
.truck extends .car{
width: 300px;
}

What is the big difference? you might ask. This option also has the problem of having both declarations 100 lines apart from each other. However, in this version, there is a clear way to know that the styles that you see for .truck are not the only ones affecting .truck, where as in the current way of doing so, there in no such visual cue.

The whole idea of classes is wrong in most programming languages, but that is material for a whole other essay.

There are many ideas that have been laid out to solve the many issues of CSS, two that come to mind are OOCSS, and Stylus. Both are worth a look.

CSS is not a programming language. Rather, it is a styling language, which was good enough for when the web was a bunch of static documents. It even made sense when the webapps where things like forums, blogs, and e-papers. Today we need a styling language that borrows ideas from programming languages. One feature that would be a first good step in the right direction is adding variables to the language, and arithmetic capabilities. Stylus implements these ideas.

CSS is a styling language, but we need it to become a state representation language. The web of today is state based, and CSS doesn’t do well in this area. Moreover, we need it to be an animation language. So far Javascript has done that job, but CSS has demonstrated that it has potential to do it to.

Another reason why I hate web development is HTML. There is a lot of excitement about HTML5, which is good, but there are fundamental flaws in the design of HTML that just make the language not suitable for the web. There are, for example, security issues with window. This could be thought of as a problem with javascript, but it is not. Javascript has no window, that is an HTML global variable. Javascript has a global object, and window refers back to that global object, but window is not part of Javascript, it is the global object implementation in HTML. HTML5 does nothing to solve this issue. Instead, it adds more complexity to a system that is in itself complex, and complexity is the first enemy of security. But there are more fundamental problems with HTML.

HTML is a very closed language. HTML has a defined set of tags. This tags have a define behaviour, and you cannot expand this tags. Technically you can, but at some point you will run into trouble. There is no way to create semantically meaningful markup with the language that we have today. This can be argued, of course, but the truth is that HTML is too small to cover the needs of developers today. In order to create meaningful markup you need to use classes, and IDs, and this becomes a problem when you are creating webapps.

Once I said that HTML5 was built for blogs. The new additions to HTML that conform the HTML5 specification has a clear influence from the blogging community. They wanted an article tag, an aside tag, a section tag, a header tag, a footer tag and all of the rest because that is what they need. If you get together with blog designers, all they talk about is content, footer, sidebars and sections. We cannot build the web on top of blogging engines.

We need a language that allows us to specify more than just content sections; we need to be able to specify UI elements other than input boxes and buttons. There are some new elements that allows us to do this, like some new form elements that promise a brighter future, but it is not enough. We should have gotten those back when the talks about web 2.0 were all over the web.

HTML is just not suited for web development today.

It seems that from the stack (HTML, CSS, and Javascript), the only language being pushed in the right direction is Javascript (actually Ecmascript). This is a good thing.

Finally, the DOM is a mess. When people say the hate Javascript, the usually mean this:

var a = document.getElementById(‘myID’);
var b = document.createElement(‘span’);
b.appendChild(document.createTextNode(‘My text’);
a.appendChild(b);

I look at them and say, please step back from the computer and read a book. That is not Javascript. What you are seeing right there, that mess is the DOM’s API.

The DOM has many design issues that are beyond my willingness to explain them. The one thing you should know about it is that it was poorly design and it’s an awful thing with which to work. It is ridiculously repetitive and has horrible method names. Don’t let people fool you into thinking that is the way to write methods, because it is not.

There are many other reasons to hate web development, like the one we call IE*, but I think you get the idea.

There are two things that need to happen for web development to really advance. The first is we need to rethink HTML and CSS, and the second is getting rid of browsers that are holding back web development. Until this happens, we will be living in a world with a wasted web.

*IE is getting better, but that is of no use when the older version stick around for too long like they do.

Notas sobre z-index

Estoy escribiendo una galería y he descubierto algo interesante. El cliente requiere que la galería sea una especie de light box por lo que tengo que trabajar con elementos transparentes. Si alguna vez has trabajado con elementos transparentes sabrás que un div con transparencia del 70% forzará a todos los elementos que contiene a tener dicha transparencia aun cuando tu especifiques que esos elementos deben ser completamente opacos. Esto trae un problema: no se pueden poner más elementos dentro del elementos transparente, por lo que este sirve solo como una pantalla. Para poder posicionar elementos sobre él y que estos no sean transparentes es necesario que se coloquen en otro contenedor y que este contenedor se posicione sobre el elemento transparente. Esto realmente no representa un problema, pero me llevó a descubrir una curiosidad sobre z-index de la que no había oído antes.

Intentando diversas opciones, llegué a considerar poner el elemento transparente con posición fixed para evitar que se mueva cuando se hace scroll y así asegurar que la pantalla esta cubierta en todo tiempo. Después quise poner el elemento que quería mostrar sobre la pantalla con su posición por defecto para poder aprovechar algunas ventajas de esta posición. Pensé que con usar un z-index de 1000 sería suficiente pero no fue así. Resulta que un elemento cuya posición no ha sido modificada (usando position en CSS)  no puede posicionarse sobre un elemento cuya posición es fixed o absolute sin importar el z-index que se le asigne al elemento cuya posición no ha sido modificada. Esto puede resultar poco interesante para muchos, sin embargo, a mi me ha tomado por sorpresa por que son de las cosas que no te enseñan en los libros y que solo aprendes con la experiencia. Lo bueno de esto es que te ayuda a conocer más la forma de funcionar del lenguaje y esto te ayuda en desarrollos futuros. Saber como funciona el lenguaje y la web en general es muy importante como lo comprueba este post:

http://www.forosdelweb.com/f13/como-obtener-dinamicamente-siguiente-nivel-con-js-765613/

Creando circulos con CSS.

Esto es solo una curiosidad que se me ocurrió ayer antes de dormir. Posiblemente ya se haya hecho antes, pero yo nunca he escuchado de ello. Se trata simplemente de crear círculos con CSS. No es nada del otro mundo, simplemente aprovechar un poco las características de CSS3, o en este caso mejor dicho, el ‘moz-border-radius que imita una característica de CSS3.

Creando un simple circulo:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta name="author" content="Buzu">
<meta name="date" content="2009-12-11T11:04:26-0800">
<meta name="copyright" content="">
<meta name="keywords" content="">
<meta name="description" content="">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8">
<meta http-equiv="content-style-type" content="text/css">
<meta http-equiv="expires" content="0">
<style type="text/css">
 .circulo{
 border: 50px solid #ccc;
 -moz-border-radius: 60px;
 width: 15px;
 background-color: #CCC;
 height: 12px;
 }
</style>
</head>
<body>
 <p class="circulo"></p>
</body>

Como puedes ver, simplemente estamos aprovechando CSS y obtenemos un círculo. Naturalmente, esto solo funciona en firefox, pero puede ser adaptado de modo que funcione en la mayoría de los navegadores más populares. Ahora veamos si podemos hacer algo más con esos círculos:

Un mono de nieve:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta name="author" content="Buzu">
<meta name="date" content="2009-12-11T11:29:47-0800">
<meta name="copyright" content="">
<meta name="keywords" content="">
<meta name="description" content="">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8">
<meta http-equiv="content-style-type" content="text/css">
<meta http-equiv="expires" content="0">
<style type="text/css">
 .cabeza{
 border: 50px solid #ccc;
 position: absolute;
 -moz-border-radius: 60px;
 top: 20px;
 left: 300px;
 background-color: #CCC;
 }
 .cuerpo{
 border: 70px solid #ccc;
 position: absolute;
 top: 110px;
 left: 280px;
 -moz-border-radius: 80px;
 background-color: #CCC;
 }
 .ojo{
 border: 5px solid #000;
 position: absolute;
 top: 50px;
 background-color: #000;
 -moz-border-radius: 6px;
 }
 .izquierdo{
 left: 330px;
 }
 .derecho{
 left: 360px;
 }
 .voca{
 border-bottom: 10px solid #F00;
 position: absolute;
 top: 80px;
 -moz-border-radius: 20px;
 width: 10px;
 left: 345px;
 }
</style>
</head>
<body>
 <p class="cabeza"></p>
 <p class="cuerpo"></p>
 <p class="ojo derecho"></p>
 <p class="ojo izquierdo"></p>
 <p class="voca"></p>
</body>
</html>

Podríamos incluso agregar un poco de javascript y hacer transiciones de cuadro a circulo o a otras formas, las posibilidades son muchas. A ti que se te ocurre?