Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS with if/then browser logic

For browsers < IE7, I want to use a certain style attribute, while for other browsers I'd like to use another. Can I do this using a single css file, or do I have to do if then logic to include an ie hack css file?

like image 982
Jeremy Avatar asked Sep 08 '09 23:09

Jeremy


People also ask

Can you do if then in CSS?

No, We can not use if-else conditions in CSS as CSS doesn't support logics. But we can use some alternatives to if-else which are discussed below: Method 1: In this method, we will use classes in HTML file to achieve this. We will define different class names according to the conditions which we want to apply in CSS.

Does CSS use conditional logic?

CSS authors use CSS conditional rules to define a set of rules based on the capabilities of a processor or document a style sheet is applied to. Some of these rules enable authors to perform logic within the style sheet.

Can browsers understand CSS?

The browser parses the HTML and creates a DOM from it. Next, it parses the CSS. Since the only rule available in the CSS has a span selector, the browser sorts the CSS very quickly!


2 Answers

Here's an example how you can include an IE6-specific CSS to override specific CSS classes for IE 6 or lower:

<link rel="stylesheet" type="text/css" href="/css/screen.css" title="MySiteStyle" media="screen" />
<!--[if lte IE 6]>
<link rel="stylesheet" type="text/css" href="/css/screen-ie6.css" title="MySiteStyle" media="screen" />
<![endif]--> 

Alternatively, you can do it on per-element basis like this:

<!--[if (!IE) | (gt IE 6)]>
<div class="header">
<![endif]--> 
<!--[if lte IE 6]>
<div class="ie6_header">
<![endif]--> 

MSDN has some more details about IE Conditional Comments support.

like image 113
Franci Penov Avatar answered Sep 17 '22 23:09

Franci Penov


Well you could use javascript to detect the browser and apply a class based on that. For example, see:

JQuery Attributes

like image 39
Gavin H Avatar answered Sep 21 '22 23:09

Gavin H