Chapter 9. Rule 7: Avoid CSS Expressions
CSS expressions are a powerful (and dangerous) way to set CSS properties dynamically. They're supported in Internet Explorer version 5 and later. Let's start with a conventional CSS rule for setting the background color:
background-color: #B8D4FF;
For a more dynamic page, the background color could be set to alternate every hour using CSS expressions.
background-color: expression( (new Date()).getHours( )%2 ? "#B8D4FF" : "#F08A00" );
As shown here, the expression
method accepts a JavaScript expression. The CSS property is set to the
result of evaluating the JavaScript expression.
The expression method is simply
ignored by other browsers, so it is a useful tool for setting properties
in Internet Explorer to create a consistent experience across browsers.
For example, Internet Explorer does not support the min-width property. CSS expressions are one way
to solve this problem. The following example ensures that a page width is
always at least 600 pixels, using an expression that Internet Explorer
respects and a static setting honored by other browsers:
width: expression( document.body.clientWidth < 600 ? "600px" : "auto" ); min-width: 600px;
Most browsers ignore the width
property here because they don't support CSS expressions and instead use
the min-width property. Internet
Explorer ignores the min-width property
and instead sets the width property dynamically based on the width of the document. CSS expressions are re-evaluated when the page changes, ...