提问人:lYriCAlsSH 提问时间:2/10/2009 最后编辑:lYriCAlsSH 更新时间:11/5/2013 访问量:5510
IE CSS 对齐问题
IE CSS alignment issues
问:
我有以下CSS,我已经用PHP“破解”了它,因为它在IE7中没有正确对齐。有没有更好的方法可以在不求助于PHP的情况下做到这一点?
#Menu
{
width: 100%;
height: 32px;
padding-top: <?php if(preg_match('/msie/i', $_SERVER['HTTP_USER_AGENT'])){echo '22px';}else{echo '40px';}?>;
padding-left: 13px;
}
我想避免使用条件注释和必须维护多个 css 文件。
答:
这个方法仍然使用一些条件注释,但至少你没有通过PHP评估你的代码。为了提供更多帮助,我需要查看完整的代码示例。
<style type="text/css">
#Menu {
width: 100%;
height: 32px;
padding-top: 40px;
padding-left: 13px;
}
</style>
<!--[if IE]>
<style type="text/css">
#Menu {
padding-top: 22px;
}
</style>
<![endif]-->
哇。是的,不要那样做。您需要考虑使用“条件注释”来包含您想要的 css。您的第一位评论者 bendewey 已经展示了如何轻松地将 IE7 作为目标。还有其他类型的条件注释,它们将允许您针对其他版本的 IE。
他们来了:
<!--[if IE]> According to the conditional comment this is Internet Explorer <![endif]--> <!--[if IE 5]> According to the conditional comment this is Internet Explorer 5 <![endif]--> <!--[if IE 5.0]> According to the conditional comment this is Internet Explorer 5.0 <![endif]--> <!--[if IE 5.5]> According to the conditional comment this is Internet Explorer 5.5 <![endif]--> <!--[if IE 6]> According to the conditional comment this is Internet Explorer 6 <![endif]--> <!--[if IE 7]> According to the conditional comment this is Internet Explorer 7 <![endif]--> <!--[if gte IE 5]> According to the conditional comment this is Internet Explorer 5 and up <![endif]--> <!--[if lt IE 6]> According to the conditional comment this is Internet Explorer lower than 6 <![endif]--> <!--[if lte IE 5.5]> According to the conditional comment this is Internet Explorer lower or equal to 5.5 <![endif]--> <!--[if gt IE 6]> According to the conditional comment this is Internet Explorer greater than 6 <![endif]-->
如果你打算对不同版本的IE进行大量调整,你可以提前计划并使用“身体类”技巧。它在标记中看起来有点丑陋,但它是一种行之有效的技术,有时它胜过拥有大量样式表和样式标签。
在这里:
<!--[if !IE]>--><body><!--<![endif]--> <!--[if IE 6]><body class="ie6"><![endif]--> <!--[if IE 7]><body class="ie7"><![endif]--> <!--[if IE 8]><body class="ie8"><![endif]-->
在样式表中,只需将类附加到选择器即可重置所需的任何样式。喜欢这个:
#some_div { margin-top:30px; } .ie6 #some_div { margin-top:40px; } .ie7 #some_div { margin-top:50px; }
希望这是有道理的。无论哪种方式,您都希望使用条件注释而不是 PHP。
评论
如果没有演示页面,真的很难说出这里发生了什么,但可能是页面上的另一个元素将其降低了 18 像素吗?难道元素上有一些默认边距吗?我想不出你给出的CSS有什么问题。子元素在IE和其他浏览器中的大小可能不同吗?
通常,当我看到开发人员在做这种事情时,那是因为他们不明白发生了什么。然后他们最终得到 3 个基本相同的 HUGE CSS 文件的独立副本;还有很多头痛。
IE条件评论在正确的方向上迈出了安全的一步;特别是 PHP 示例中的浏览器嗅探注定要失败,因为无法保证用户代理字符串。
我给你最好的建议是花时间通读一下非常无聊的 W3C CSS 文档,如果只是关于 DISPLAY BLOCK 和 INLINE 模式的章节。一旦你读到这一点,90%的css布局问题就会得到解决。剩下的就是习惯最常见的IE6错误,即“布局”模式。
#some_div {
_margin-top:40px; //Only works on IE6
*margin-top:30px; //Only works on IE7-IE6
margin-top:20px\9; //Only works on IE8-IE7-IE6
margin-top:10px; //Works on all others
}
评论