Internet Explorer和浮动:请解释

时间:2009-05-06 00:11:36

标签: html css internet-explorer cross-browser

昨天有人问Width absorbing HTML elements。我提出了two solutions:一个基于表和一个纯CSS。现在纯CSS一体在Firefox和Chrome中运行良好,但在IE中却不行。

基本上浮子被撞到下一行。这是我的理解(以及FF和Chrome的行为),这不应该是这种情况,因为左边的div是块级元素,浮动应该基本上忽略。

完整的代码示例如下。添加DOCTYPE以强制IE进入符合标准的模式有点帮助,但问题仍然存在。

所以我的问题是:我是否误解了我对浮动的理解,还是IE的问题?

更重要的是,我如何在IE中使用它?这一直困扰着我。

<html>
<head>
<style type="text/css">
div div { height: 1.3em; }
#wrapper { width: 300px; overflow: hidden; }
div.text { float: right; white-space: nowrap; clear: both; background: white; padding-left: 12px; text-align: left; }
#row1, #row2, #row3, #row4, #row5, #row6 { width: 270px; margin-bottom: 4px; }
#row1 { background: red; }
#row2 { background: blue; }
#row3 { background: green; }
#row4 { background: yellow; }
#row5 { background: pink; }
#row6 { background: gray; }
</style>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
google.setOnLoadCallback(function() {
  $(function() {
    $("div.text").animate({ width: "90%" }, 2000);
  });
});
</script>
</head>
<body>
<div id="wrapper">
<div class="text">FOO</div><div id="row1"></div>
<div class="text">BAR</div><div id="row2"></div>
<div class="text">THESE PRETZELS ARE</div><div id="row3"></div>
<div class="text">MAKING ME THIRSTY</div><div id="row4"></div>
<div class="text">BLAH</div><div id="row5"></div>
<div class="text">BLAH</div><div id="row6"></div>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:7)

由于行上的width: 270px,浮动正被撞到下一行。这种情况发生在IE6 / 7中,因为它的broken float model。 IE将浮动元素放在彩色行div旁边而不是覆盖它们,但由于它们的组合宽度大于包装器的宽度,彩色行会下降到下一行。

如果您确实需要这些彩色条的最大宽度为270像素,则可以使用max-width代替。但是,这在IE6中不起作用,所以如果这非常关键,那么你需要解决这个问题。

答案 1 :(得分:0)

不确定为什么你试图以这种方式实现它。 但这很有效。

<html>
<head>
<style type="text/css">
div div { height: 1.3em; }
#wrapper { width: 300px; overflow: hidden; }
div.text { float: right; white-space: nowrap; clear: both; background: white; padding-left: 12px; text-align: left; }
#row1, #row2, #row3, #row4, #row5, #row6 { width: 270px; margin-bottom: 4px; }
#row1 { background: red; }
#row2 { background: blue; }
#row3 { background: green; }
#row4 { background: yellow; }
#row5 { background: pink; }
#row6 { background: gray; }
</style>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
google.setOnLoadCallback(function() {
  $(function() {
    $("div.text").animate({ width: "90%" }, 2000);
  });
});
</script>
</head>
<body>
<div id="wrapper">
<div id="row1"><div class="text">FOO</div></div>
<div id="row2"><div class="text">BAR</div></div>
<div id="row3"><div class="text">THESE PRETZELS ARE</div></div>
<div id="row4"><div class="text">MAKING ME THIRSTY</div></div>
<div id="row5"><div class="text">BLAH</div></div>
<div id="row6"><div class="text">BLAH</div></div>
</div>
</body>
</html>