Pages

SPONSORED

Expressions in CSS

CSS Expressions, also called Dynamic properties are used to assign CSS code with calculated and dynamic values. CSS Expressions are JavaScript embedded within CSS. They are completely JavaScript dependent. Values are assigned to CSS code through JavaScript calculations during run time.  

<DIV ID="myDiv"
  STYLE="left:expression(document.body.clientWidth/2-oDiv.offsetWidth/2);
         top:expression(document.body.clientHeight/2-oDiv.offsetHeight/2)">
My text goes here...
</DIV>

Is it really good?
We just discussed that expressions are JavaScript dependent. This means that it required the browser to keep JavaScript enabled on running the pages using expressions. Expressions will not be functional if JavaScript is disabled.

We may feel that expressions are calculated once when the control loads or at event where we have implemented it to be fired. That is not true. Expressions are evaluated consistently when we are on the web page. Even a simple operation like scroll, hover over the control etc will cause the expression evaluation.This is easily observed if expressions are used to freeze data grid headers in aspx pages. Each time you scroll you can observe a shake on the header. This makes use of most of our client resources. Next time if you notice any slowdown in your browser and not able to find any reason, look for expressions.

Then why do developers use this?
Internet Explorer version 7 and below are not fully compliant with cascading style sheets (CSS) and hence we had to go with alternate and easy way of using expressions in CSS.

Is there any alternate for IE7 and below?
JavaScript can be used directly in most of the cases instead of CSS expressions. The above example can be implemented in JavaScript as given below –

window.onload = setWidth;

Function setWidth(){
document.getElemenById(“myDiv”).style.left = body.clientWidth/2-oDiv.offsetWidth/2;
document.getElemenById(“myDiv”).style.top = document.body.clientHeight/2-oDiv.offsetHeight/2;
}


CSS Expressions are no longer supported in IE8. However it can be made to work by running Internet Explorer in IE7 mode or below. We know that expressions in CSS hit performance. Despite that sometimes we will need to end up going for it. However before writing expressions just remember that they affect performance and are less reliable. Always consider JavaScript instead.