Reputation: 445
I can't seem to get clear:both
to avoid having multiple floated elements colliding with each other. For example, with this 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&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&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>
I'm trying to enforce that any paragraph as at most one .alignleft
or .alignright
image floating beside it, but the clear:both
for the .alignright::before
doesn't seem to be enough to shift the second figure down to start below the bottom of the .alignleft
figure
I've tried assigning the clear:both
class to the .alignleft
elements, as well as to the ::before
pseudoelements. I'm not sure what other magic I need to try.
Because the HTML is created by the default WordPress editor, I'd really like to avoid any solution that requires a change to the element structure. I want to solve this strictly through CSS styles.
Upvotes: 0
Views: 169
Reputation: 13536
Is this the behavior you look for?
.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&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&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>
Upvotes: 1