简体   繁体   中英

In css, how do I make one line only execute if it is IE6 or IE7

I have this code:

#left-nav #left{
  width:100px;
  height: 99px;
  float:left;
  border-bottom: 1px solid #344a53;
  margin-top:-1px;
}

I want to be able to only do the margin-top:-1px if it is not IE7 or IE8. Also does anyone know this problem with cross browser compatibility? I have to divs side by side in another div, but for some reason in chrome firefox and IE8, I have to use the margin-top: -1px because the div on top was 1 pixel down.

Example:

<div id="header"></div>
<div id="container">
<div id="left"></div>
<div id="right"></div>
</div>

The left and right div for some reason is 1 pixel from touching the header, but the container still touches it perfectly.

Quick and easy way is to use the IE conditionals.

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

You can also use stuff like

<!--[if IE lte 7]>

For if IE is version 7 or lower.

See http://www.quirksmode.org/css/condcom.html for more information

Use conditional comments to target the CSS to IE6/7:

<!--[if IE 6]><link rel="stylesheet"  type="text/css" media="all" href="ie.css" /><![endif]-->
<!--[if IE 7]><link rel="stylesheet"  type="text/css" media="all" href="ie.css" /><![endif]-->

And then in ie.css you'd have this rule:

#left-nav #left{
    margin-top: 0;
}

You'd have to make sure that the ie.css file is included after your main css file so it overrides the margin-top: -1px .

On the topic of the negative margin, I try not to use them as they tend to cause problems. It's much safer to use:

#left-nav #left{
    position: relative;
    top: -1px;
}

Answering the question in your title you can apply a property to only IE 6 and 7 by using the star hack provided you are down with having invalid CSS.

This approach has the advantage that it doesn't require you to remember to use conditional comments in each page you include your CSS with.

Hacks work, but why not reconsider what you've already done to avoid them? Using a framework with auto padding and defined spaces such as Blueprint, YUI, or 960 grids can help immensely and avoid hacks....especially on Blueprint and YUI with their browser "resets" Using these and simple, straightforward css, I honestly can't remember the last time I used a hack--it's been over a year for sure.

If I was a betting man, I'd say there's something going on with your float in the side-by-side example you mentioned. Try a simple float reset test:

.clear {
  clear: both;
}

and then after the side by side divs, insert

<div class="clear"></div>

If you notice any change, it was a float issue. Pretty common issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM