How to make an element fill the remaining space of the last line of a multi-line paragraph with CSS?

There have been many questions about how to fill space with CSS, this being the main one I think. These days flexbox provides a great and easy solution. However, it doesn't let you fill the remaining space of a multi-line paragraph. To be clear, this what I want:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vel scelerisque purus, et ultricies sapien. Donec mi augue, pulvinar at mauris sit amet, ultricies molestie nisi. Cras et nisi lobortis. FILL FROM HERE TO THE END ->

I found one question asking the same, however it fills space with a CSS content rule, and I need to be able to fill it with an element (specifically an <input>, if that matters.)

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Quisque vel scelerisque purus, et ultricies sapien. Donec mi
augue, pulvinar at mauris sit amet, ultricies molestie nisi.
Cras et nisi lobortis.
<input type="text">
</p>

My current solution is to add a span between the end of the text and the <input>, measure it's position, and manually set a width, however that requires me to listen for browser resize events and recalculate the width. If it was possible to do this entirely within CSS, that would be great. If extra elements have to be added that's fine.


Solution 1:

Wrapping each word in a span works too -- might even be a slightly better approach. There are a lot of ways to do the wrap, here's a purely javascript one.

Essentially, since each word is a span, flexbox can determine the leftover spacing at the end of the last word. Simply add flex-grow: 1 to the input so that it fills the remaining space.

Note that you'll need to add padding-right to each span to add a space between the words.

const p = document.getElementById("p");
const str = p.innerText.replace(/\S+/g, "<span>$&</span>");

p.innerHTML = str;
p.innerHTML += '<input class="input" type="text" />';
p {
  display: flex;
  flex-wrap: wrap;
}

p span {
  padding-right: 3px; /* space size */
}

input {
  width: 0;
  flex-grow: 1;
}
<p id="p">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vel scelerisque purus, et ultricies sapien. Donec mi augue, pulvinar at mauris sit amet, ultricies molestie nisi. Cras et nisi lobortis.
</p>