【问题标题】:Floating elements around a previous element in markup标记中前一个元素周围的浮动元素
【发布时间】:2012-02-11 23:39:41
【问题描述】:

我为标题、图像和一些文本 (example) 提供了一些相当基本的标记:

<div>
  <h1>
  <img>
  <p>
</div>

我想在不更改 HTML 的情况下将图像浮动在前面的标题 后面的段落的左侧。

理想情况下,我只是将图像向左浮动:

img {
  float: left;
}

但由于标头出现在标记中的图像之前,因此标头会跨越整个容器:

/-----------------------------------------\
| Header Header Header                    |
| |-------|                               |
| |-Image-|  Paragraph text               |
| |-------|  Paragraph text               |
| |-------|  Paragraph text               |
\-----------------------------------------/

我希望它看起来像:

/-----------------------------------------\
| |-------|  Header Header Header         |
| |-------|                               |
| |-Image-|  Paragraph text               |
| |-------|  Paragraph text               |
| |-------|  Paragraph text               |
\-----------------------------------------/

My efforts so far (Dabblet)

我可以将&lt;h1&gt; 浮动到右侧,但图像的宽度会有所不同,因此我无法为元素指定恒定的宽度。我宁愿保留上述标记顺序,因为它在语义上更有意义,并且当显示无样式时。

【问题讨论】:

    标签: css css-float


    【解决方案1】:

    到目前为止,这是我的解决方案。

    你可以在这里找到它:http://jsfiddle.net/gHNdJ/

    希望这就是您要搜索的内容。

    注意:如果您仍然想保持这样的html,那么第一个答案的解决方案是迄今为止最好的。但我不喜欢使用定位。

    【讨论】:

    • 如果&lt;img&gt; 在标记顺序中位于&lt;h1&gt; 之前——就像在您的解决方案中一样——CSS 可以简单地简化为将&lt;img&gt; 浮动到左侧。您对包含&lt;div&gt; 元素的使用使解决方案过于复杂,不幸的是,当&lt;h1&gt; 出现在图像之前时,该解决方案仍然不起作用;_;
    【解决方案2】:

    这里是one possible way

    标记:

    <div>
        <h2>This is my title</h2>
        <img src="http://dummyimage.com/320x200/ff00ff/fff&text=woooo!" alt="sample" />
        <p>I'd like to float the image left of both the preceding header and the succeeding paragraph, without changing the HTML. I'd like to float the image left of both the preceding header and the succeeding paragraph, without changing the HTML. I'd like to float the image left of both the preceding header and the succeeding paragraph, without changing the HTML. I'd like to float the image left of both the preceding header and the succeeding paragraph, without changing the HTML.</p>
    </div>
    

    CSS:

    div { position: relative; }
    img { float: left; margin-right: 20px; }
    p { position: relative; top: 24px; }
    h2 { position: absolute; left: 340px; font-weight: bold; }
    

    视觉示例(在 Firefox 中):

    【讨论】:

    • 感谢您的回答,但设置&lt;h2&gt; 元素的左边距以模拟浮动只有在图像具有固定宽度时才有效;_;
    • 是的,如果宽度发生变化,并且h2 超过 1 行,则此解决方案会出现问题:/
    猜你喜欢
    • 1970-01-01
    • 2015-03-27
    • 2011-11-06
    • 2012-08-18
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 2012-03-13
    • 2012-09-26
    相关资源
    最近更新 更多