skip to Main Content

Imagine I have the following HTML:

<span>one two</span> <span>three four</span>

If the user presses control-F (or command-F on macOS), they can search for "two three" and it will successfully find/match the text across the two spans.

How can I insert a line-break in between the spans (so that "three" starts on a new line), while still making sure that the user can find the text with control-F the same way as before?

If I insert a <br> tag, or change the style of the spans to display: block, for example, then it no longer works. I can only find/match text within a single span. (In some cases, Chrome does allow me to paste a newline character into the find dialog — even though I can’t type it myself — or I can find "twothree", but I want to be able to find the text as if there’s a space in between: exactly "two three")

I’m willing to change the structure of the HTML if necessary.

2

Answers


  1. I’ve found a solution using the <wbr> element and a little bit of JavaScript.

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr

    Here is the code :

    let element = document.getElementById("paragraph"); // Get the element
    let width = element.offsetWidth; // Get the current width of the element
    element.style.width = width - 1 + "px"; // Set the new width to be the original width minus 1px
    #paragraph {
      white-space: nowrap; 
      width: fit-content
    }
    <p id="paragraph">
      one two<wbr /> three four
    </p>
    Login or Signup to reply.
  2. Works with display:inline-block though:

    span {display:inline-block; width:100%}
    <span>one two</span> <span>three four</span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search