防止 "fragmentation" 浮动图像旁边的换行文本

Prevent "fragmentation" of wrapped text next to floated image

我正在尝试让此文本在较小的分辨率下不 "fragment"。这是作业,我只能使用 XHTML。

右边的图片是这样浮动的:

#image {
    width:420px;
    margin-left: 2%;
    height:370px;
    position:relative;
    float:right;
}

使用 XHTML:

      <div id="image">
        <a href="http://en.wikipedia.org">
          <img src="picture.png"/>
        </a>
      </div>   

    <p><a href="https://en.wikipedia.org/wiki/Lorem Ipsum">Lorem</a> ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

显然这个 "fragmentation" 不会出现在更大的分辨率上。

在 CSS2.1 中有一个优雅的方法吗?

由于环绕问题取决于分辨率,您可以使用 CSS 媒体查询轻松解决此问题。将这些视为 css 的简单 "if/else"。

因此计算出 window 宽度,在该宽度处包装变得不可接受,并使用该数字创建一个 max-width 规则。这意味着如果宽度小于您的最大尺寸,规则将适用。

现在在这个尺寸下,只需删除浮动并将图像设置为显示块,这会将文本向下推到页面下方。

@media (max-width: 600px) {
  #image {
    display:block; // make image push text down
    float: none; // remove your float
    margin: 10px auto; // center the image in the available space
  }
}

注意:媒体查询应该位于 CSS 的底部,这样它们会覆盖以前的规则,并且您只需要更改被覆盖的属性。

不错的解决方案@BryceHowitson。

我刚刚一直在努力解决这个问题,并提出了您的方法的变体。我将媒体查询放在图像后面的文本段落中。

我的解决方案针对浮动图像后面段落中的清晰 属性。当屏幕分辨率在浮动图像旁边留下足够的 space 以令人满意地呈现文本时,段落环绕图像。当可用宽度太小而无法令人满意地呈现文本时,该段落已应用 "clear:both",并且该段落会向下移动到浮动图像下方。

此方法的一个 'pro' 是 CSS 规则应用于我们试图控制其行为的元素。

然而,@BryceHowitson 的解决方案实现的是当后续文本的环绕关闭时图像居中。

CSS

.p-clear {
    @media (min-width: 400px) {
        clear: none;
    }
    @media (max-width: 400px) {
        clear: both;
    }
}

HTML

<img src="..." width="300px">
<p class="p-clear">text that needs at least 100px width</p>