HTML If Conditions & Statements

Published September 16th 2009 by
Filed under HTML

Like Java and other programming languages, HTML also has its own set of If Conditions and Statements. They’re really simple to use and are useful if you want to have a page look the best it can in different browsers.

For example, Internet Explorer 6 and below can’t handle transparent PNG images but Internet Explorer 7 and above can, so you may want to remove the transparent PNG in Internet Explorer 6 and below.

To do this, you can use the following If Statements:

<!--[if gt IE 7]>
<TABLE style="background: url(images/gradient.png);" BORDER="0" CELLPADDING="0" CELLSPACING="0">
<![endif]-->

This code is read as it’s written. It means if the browser you’re using is greater than Internet Explorer 7, use the PNG image background. Internet Explorer 6 and below will not use the PNG background.

Different conditions you can use are:

[if IE] – Checks if the browser is Internet Explorer
[if IE 7] – Checks if the browser is Internet Explorer 7
[if !IE] – Checks if the browser is not Internet Explorer
[if lt IE 5.5] – Checks if the browser is less than IE 5.5
[if lte IE 6] – Checks if the browser is less than or equal to IE 6
[if gt IE 5] – Checks if the browser is greater than IE 5
[if gte IE 7] – Checks if the browser is greater than or equal to IE 7
[if !(IE 7)] – Checks if the browser is not Internet Explorer 7
[if (gt IE 5)&(lt IE 7)] – Checks if the browser is greater than IE 5 and less than IE 7
[if (IE 6)|(IE 7)] – Checks if the browser is IE 6 or IE 7
[if true] – Evaluates if a condition is true
[if false] – Evaluates if a condition is false

These conditions can be substituted into the example above. Firefox cannot handle If Statements but when the IGNORE operator is used within the If Statement, it can read what is contained within it.

So if you wanted to display the transparent PNG background in Firefox but not Internet Explorer, you can add the following If Statement:

<!--[if gt IE 7]> <![IGNORE[--><![IGNORE[]]>
<TABLE style="background: url(images/gradient.png);" BORDER="0" CELLPADDING="0" CELLSPACING="0">
<!--<![endif]-->

Be sure to change the End If part from <![endif]–> to <!–<![endif]–>.