JavaScript in CSS, Ugly But Interesting

May 12, 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.


comments powered by Disqus