代码之家  ›  专栏  ›  技术社区  ›  Steve Dwire

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

  •  0
  • Steve Dwire  · 技术社区  · 6 年前

    我好像不明白 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 图像漂浮在它旁边,但是 清除:两者 对于 .alignright::before 似乎不足以将第二个数字下移到 .左对齐 图形

    我试过分配 清除:两者 班级到 .左对齐 元素,以及 ::before 假元素。我不知道我还需要尝试什么魔法。

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ilya Streltsyn    6 年前

    这是你想要的行为吗?

    .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>