CSS – Why Doesn’t CSS Natively Support Variables and Hierarchy?

coding-stylecsscss3ui

I am new to UI development, but I feel very uncomfortable with how CSS works.

My use case is that I wanted to apply some specific styles inside a particular div on a page.

CSS attempt:

div.class1 {
    font: normal 12px arial, helvetica, sans-serif;
    font-color: #f30;
}
div.class1 div.class2 {
    border: 1px solid #f30;
}

LESS attempt:

@red: #f30;
@font-family: arial, helvetica, sans-serif;
div.class1 {
    font: normal 12px @font-family;
    font-color: @red;
    div.class2 {
        border: 1px solid @red;
    }

The CSS version can induce bugs, since it forces you to repeat #f30 & div.class2 every time you try to achieve hierarchy and variable re-use.

My questions:

  • Why is that CSS makes things difficult?
  • LESS does nothing special – just makes obvious improvements and translates to CSS?
  • What is that CSS wants to motivate in users because of which it promotes such a redundant coding style?

I strongly believe CSS should be what LESS is. Definitely I am overlooking some obvious advantage of why things are done that way in CSS. I thought it was a legacy problem, but I was surprised when I saw no attempts to solve this with CSS3.

Please help me understand how should I approach CSS?

Best Answer

CSS isn't trying to make things more difficult on purpose, it was designed with a far simpler goal in mind, variables and hierarchies are hardly its only shortcomings. LESS and Sass exist specifically to address these shortcomings, and until either capability is natively supported, you should stick with them.

That said, W3C's CSS Working Group is working on drafts for both CSS variables and CSS hierarchies:

There's absolutely no way to tell when either draft will be ready for implementation, or how soon major browsers will adopt them. All I can say is that the CSS Variables draft is closer to being adopted, you can already test drive CSS variables in Chrome, Safari and Firefox, but keep in mind that support in all three browsers is considered experimental and subject to change. Read Using CSS variables on MDN for more details.

Related Topic