Welcome to dtsn.co.uk, if your new here please subscribe to my feed
12/05/2008

There is a very little used and unknown method which allows you to utilise JavaScript within a CSS file. The CSS Expression property allows you to assign a JavaScript expression to a CSS property. For example, this allows you to set the position of an element according to the browser size.

width:expression(document.body.clientWidth > 950 ? "950px": "100%" );

Do not use CSS Expression, they are unreliable, slow and are only supported in IE!

CSS Expression suddenly came to me as a solution for the currently much debated feature (here and here) of variables in CSS3. This could theoretically be currently achieved through the use of CSS Expressions.

function blue() {
return 'blue';
}

body { background: expression(blue()); }

CSS Expressions are horrible and unsupported, so please don’t use them in development. They do, however, highlight a interesting and little known feature of CSS.

Promote
Jos Hirth

That’s indeed a really interesting idea. I thought about CSS variables and math ops a lot recently, but JS never crossed my mind. Since it runs on the client side you can’t be sure that it’s actually executed. But it’s probably good enough for proof of concept things.

The name of the function in your example is bad though. You should have called it primaryColor or something like that. ;)

BTM

only use of Expressions I’ve seen thats interesting is mimicking `position: fixed` by calculating the page offset anf changing element position. Dont really see any other uses as it’s a IE only thingy and will prolly never by implemented in anything else as it’s not standard compilant.

Daniel

@BTM as Jos says this is more of a concept rather than an actually use. If this was widely supported it could be a much more powerful tool in defining CSS variables, they could be conditional variables such as a colour changer for a web page. However as you rightly say they aren’t supported and in fact horrible. CSS and JavaScript should be split and not live together!

Tiago Albineli Motta

If its only supported in IE, it doesnt exists for me

Comment