为什么不清除:两者都消除了这种重叠?

时间:2018-07-02 19:31:04

标签: html css

我似乎无法获得clear:both来避免多个浮动元素相互碰撞。例如,使用以下HTML:

.alignleft {
  float: left;
}

.alignright {
  float: right;
}

.alignright::before,
.alignleft::before {
  clear: both;
  content: ' ';
}
<figure class="wp-caption alignleft">
  <img src="https://placehold.it/92x217&amp;text=92x217" />
  <figcaption>With a caption</figcaption>
</figure>
<p>Paragraph related to the left-aligned image with a caption.</p>
<p>Another paragraph</p>
<p>Below is a right-aligned image with a caption</p>
<figure class="wp-caption alignright">
  <img src="https://placehold.it/92x217&amp;text=92x217" />
  <figcaption class="wp-caption-text">With a caption</figcaption>
</figure>
<p>Paragraph related to the right-aligned image with a caption.</p>
<p>Another paragraph</p>

我正在尝试强制将任何段落最多浮动在其旁边的一个.alignleft.alignright图片,但是clear:both的{​​{1}}似乎没有足以将第二个图形向下移动以从.alignright::before图形的底部开始

我尝试将.alignleft类分配给clear:both元素以及.alignleft伪元素。我不确定我还需要尝试其他什么魔术。

因为HTML是由默认的WordPress编辑器创建的,所以我真的很想避免任何需要更改元素结构的解决方案。我想通过CSS样式严格解决这个问题。

1 个答案:

答案 0 :(得分:1)

这是您寻找的行为吗?

.alignleft {
  float: left;
}

.alignright {
  float: right;
}

/* enforce that any paragraph as at most one
   .alignleft or .alignright image floating beside it */ 
.alignleft, .alignright {
   clear: both;
}
/* assuming that the paragraps are related to the figure before them,
   enforce that paragraps related to left-floated figure
   aren't beside the right-floated figure, and vice versa */
.alignright + p {
  clear: left;
}
.alignleft + p {
  clear: right;
}
<figure class="wp-caption alignleft">
  <img src="https://placehold.it/92x217&amp;text=92x217" />
  <figcaption>With a caption</figcaption>
</figure>
<p>Paragraph related to the left-aligned image with a caption.</p>
<p>Another paragraph</p>
<p>Below is a right-aligned image with a caption</p>
<figure class="wp-caption alignright">
  <img src="https://placehold.it/92x217&amp;text=92x217" />
  <figcaption class="wp-caption-text">With a caption</figcaption>
</figure>
<p>Paragraph related to the right-aligned image with a caption.</p>
<p>Another paragraph</p>