Home > Designing, Others > Float Element in the Middle of a Paragraph

Float Element in the Middle of a Paragraph

November 4th, 2019 Leave a comment Go to comments

Say you want to have an image (or any other element) visually float left into a paragraph of text. But like… in the middle of the paragraph, not right at the top. It’s doable, but it’s certainly in the realm of CSS trickery!

One thing you can do is slap the image right in the middle of the paragraph:

<p>
  Lorem ipsum dolor sit amet consectetur, adipisicing 
  <img src="tree.jpg" alt="An oak tree." />
  elit. Similique quibusdam aliquam provident suscipit 
  corporis minima? Voluptatem temporibus nulla
</p>

But that’s mega awkward. Note the alt text. We can’t have random alt text in the middle of a sentence. It’s semantically blech and literally confusing for people using assistive technology.

So what we have to do is put the image before the paragraph.

<img src="tree.jpg" alt="An oak tree." />

<p>
  Lorem ipsum dolor sit amet consectetur, adipisicing 
  elit. Similique quibusdam aliquam provident suscipit 
  corporis minima? Voluptatem temporibus nulla
</p>

But when we do that, we aren’t exactly floating the image in the middle of the paragraph anymore. It’s right at the top. No margin-top or vertical translate or anything is going to save us here. margin will just extend the height of the floated area and translate will push the image into the text.

The trick, at least one I’ve found, is to leverage shape-outside and a polygon() to re-shape the floated area around where you want it. You can skip the top-left part. Using Clippy is a great way to get a start to the polygon:

But instead of the clip-path Clippy gives you by default, you apply that value to shape-outside.

That should be enough if you are just placing a box in that place. But if it’s literally an image or needs a background color, you might also need to apply clip-path and perhaps transform things into place. This is where I ended up with some fiddling.

See the Pen
Float cutout in middle of paragraph.
by Chris Coyier (@chriscoyier)
on CodePen.

The post Float Element in the Middle of a Paragraph appeared first on CSS-Tricks.

Categories: Designing, Others Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.