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:
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 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
property here because they don’t support CSS expressions and instead use
min-width property. Internet
Explorer ignores the
and instead sets the
width property dynamically based on the width of the document. CSS expressions are re-evaluated when the page changes, ...