css - 标记中前一个元素周围的 float 元素

标签 css css-float

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

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

我想在不更改 HTML 的情况下将图像 float 到前一个标题后一段的左侧。

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

img {
  float: left;
}

但是因为 header 出现在标记中的图像之前,所以 header 将跨越整个容器:

/-----------------------------------------\
| 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)

我可以 float <h1>向右,但图像的宽度会有所不同,因此我无法为元素指定恒定宽度。我宁愿保留上面的标记顺序,因为它在语义上更有意义,并且在显示无样式时。

最佳答案

这里是 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 中):

example

关于css - 标记中前一个元素周围的 float 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8890034/

相关文章:

mobile - 使用媒体查询引入新元素

html - CSS多个浮点: left issue

具有不同高度的 CSS Floating Div 与它们之间的空间对齐

html - CSS float 未在 Chrome 中应用...错误或用户错误?

css - 为什么很清楚 :both but not clear:left in clearfix?

css 类来淡化背景颜色

css - 将文本从 BreadCrumb 移到左侧

android - 如何在 Android webview 中显示印地文字体

css - 可点击站点 - 工作表超链接

html - 如何对齐 float 的div