Value calculation for CSS

why it is not possible to do something like this in CSS: line-height: (height / 2)px;

Because that would make it very easy to introduce logical loops.

In this example, unless you explicitly set ‘height’ (in which case it would also be easy to explicitly set ‘line-height’), the height of the element is dependent on the line-height of its content text, which is dependent on the height...

IE tried to provide this with the ‘expression()’ syntax, but it doesn't really work. IE's approach was to have it recalculate step by step, so if you have an indeterminate expression it can keep redrawing your elements constantly as the expression's value changes. For an example of how this can go wrong, try:

<div id="q" style="background: yellow; line-height: expression(document.getElementById('q').offsetHeight/2+'px');">
    Lorem ipsum fiddly boing bum dfg dsfgasdf fg asdfas.
    Lorem ipsum fiddly boing bum dfg dsfgasdf fg asdfas.
    Lorem ipsum fiddly boing bum dfg dsfgasdf fg asdfas.
</div>

As you resize the browser window, the line-height, and hence offsetHeight will change, resulting in inconsistent layout. At a certain size the height will explode.

There is a case for allowing simple expressions containing only constants, eg.:

line-height: (1em+4px);

but anything involving dynamically-calculated properties is as doomed to failure as IE's infamously-broken ‘expression()’ syntax.


You might be interested in languages that compile to CSS, such as SASS, LESS or Stylus.


CSS3.1 defines calc() - it does exactly what you ask for. http://www.w3.org/TR/css3-values/#calc


I'd say it is because CSS just defines how something is displayed by the browser. There is no flow of information back to the style sheets, or to say it in other words: CSS is not dynamic.

If you know the height of an element and want to change it everytime the page is displayed you can generate a style sheet with PHP or other languages. Then you also know what's the half of the height and can set it also.

If you don't know the height it would be a dynamic change. The browser would have to render the page at first, then determine the height of the element and send it back to CSS. There the line-height is computed and altered in the rendered page. But maybe therefore the overall height of the element changes , too. Now the browser had to go back to CSS again and so on...

Just would not work. CSS is there to define the look of the page statically.

Tags:

Css