【发布时间】:2013-01-28 19:18:39
【问题描述】:
在图像周围简单地浮动文本,但在 IE7 中并不顺利。文本被推到图像下方,好像没有浮动。
根据我的阅读,造成这种情况的原因可能是图像和文本位于浮动(和固定宽度/高度)的 div 内,这可能会触发包含 div 的“hasLayout”。我一直在寻找一个干净的解决方法,但还没有找到。
在最坏的情况下,我想我可以使用 jQuery,因为我已经在页面上使用了它,但我更愿意用 CSS 来解决这个问题。
Here is a fiddle,在良好的浏览器中运行良好,但在 IE7 中应该会失败。
好(Firefox、Safari、Chrome、Opera、IE8+):
不好(IE7):
HTML:
<html>
<body>
<div id="box_section">
<div id="container1">
<div id="container2">
<div class="box">
<img src="http://c69282.r82.cf3.rackcdn.com/robot.jpg"/>
<p>Lorem ipsum etc etc whatever.</p>
</div>
<div class="box">
<img src="http://c69282.r82.cf3.rackcdn.com/pushing278.jpg"/>
<p>Lorem ipsum etc etc whatever.</p>
</div>
</div>
</div>
</div>
</body>
</html>
CSS:
/* Container for floating boxes */
#box_section
{
height: 300px; /* Fixed height and width */
width: 984px;
margin-top: 35px;
padding: 0;
overflow: hidden;
margin-left: auto;
margin-right: auto;
}
/* Containers used to centre floated items independent of number */
/* In real webpage there can be any number of boxes. */
#container1
{
padding: 0;
float:left;
width:100%;
overflow:hidden;
position:relative;
}
#container2
{
clear:left;
float:left;
padding:0;
position:relative;
left:50%;
}
/* The box. OMG. */
.box
{
float: left;
position:relative;
right:50%;
height: 190px; /* Note fixed height and width */
width: 350px;
border-style: solid;
border-color: #ebead4;
border-width: 1px;
padding-top: 10px;
padding-left: 10px;
padding-right: 10px;
margin: 20px;
overflow: hidden;
}
/* Goal is to float text around image. Note that images have fixed width/height.
Images snatched from random website for demonstration purposes. */
.box img
{
float: left;
margin-right: 15px;
height: 180px;
width: 200px;
border-style: solid;
border-radius: 5px;
border-color: #eeeeff;
border-width: 1px;
}
请注意,包含 div 的解决方案必须非常灵活,因为可以有任意数量的这些框,并且它们必须浮动在中心(使用 jQuery 一次只能显示一行)。这些框也可以是 4 种不同的固定宽度中的任何一种。
此外,由于图像可以是 2 种宽度之一(2 个不同的 CSS 类),或者根本不存在,这使情况更加复杂。我想过让图像位置绝对并用边距来做,但因此失败了。
【问题讨论】:
-
奇怪地在 IE7 中工作正常。我建议删除 position: relative on .box asit 似乎不需要,并且还考虑添加一个 css 重置文件或至少声明“* {margin:0;padding:0;}”
-
哦,对不起,我有“* {margin:0;padding:0;}”。关于相对位置,这只是我试图通过图像的绝对定位来解决这个问题的残余。对不起。不知道为什么它在 IE7 中对你有用,但我没有尝试过 IE7 中的小提琴,因为 IE9 的兼容模式不允许我(这是我拥有的最古老的 IE)。
-
您的页面中声明了有效的文档类型吗?
-
@Billy Just html,我正在使用 html5 和 shiv。实际上我发现了这个位置:relative 对于盒子的居中工作是必要的(显然在任何浏览器中)
标签: css css-float internet-explorer-7