What if CSS was imperative?

Alvaro Montoro - Apr 9 '20 - - Dev Community

Many developers (especially back-end developers) often dismiss web development in general (and CSS in particular) as a lesser branch of software development. I find interesting that the people that diminish it as something easy or simple are often the same people that make comments such as, "CSS is too difficult."

How can something be too easy and too difficult at the same time?

And we see it every day in web programming. New tools are created to get rid of CSS's difficulty/complexity, and those tools end up adding new layers of complexity (although maybe not in the eyes of the user.)

There are many reasons why this mismatch with CSS could happen: misconception, threat response, lack of interest, lack of understanding...

This last reason came as a realistic possibility: maybe people that are used to a more imperative language syntax have issues understanding a different type or approach to programming.

This is a declarative approach with some CSS code to add color to a post and to show/hide an element when an action (mouse over) is performed by the user:

#post {
  color: blue;
}

.socialLink {
  display: none;
}

#post:hover .socialLink {
  display: block;
}
Enter fullscreen mode Exit fullscreen mode

Imagine that you could get the same code written in a more imperative way. Say something like the pseudo-JavaScript-ish code below. It has the same number of lines, but it is quite more verbose:

if (this.id === "post") {
  this.color("blue");
}

if (this.className === "socialLink") {
  this.hide();
  if (this.parent().id === "post") {
    this.parent()
        .addEvent("mouseover", function() { this.show(); });
        .addEvent("mouseout",  function() { this.hide(); });
  }
}
Enter fullscreen mode Exit fullscreen mode

Ignoring performance/syntax of this pseudo-language, would you consider this more imperative approach easier?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .