Search code examples
htmlcssinline

Stylize the break of an inline element


I have a <div> that wraps two <span>s (or more). If the width of both <span>s exceeds the width of their parent <div>, then they wrap as you would expect an inline element to. However, I'm applying a border and a background color to each <span>. As a consequence of the line wrapping, the border breaks and then continues on the next line, as well as the background.

As per the first half of the example image, you can see the the background color stops immediately after the last character on the first line, with no padding, and no border to the right of it. At the beginning of the next line, the border and background starts immediately before the first character, with no padding.

Drawing from the example of what I'd want it to look like in the second half of the image, what I'd like is a way to add padding and a border to where the line breaks are, so that the line breaks look like two visually distinct <span>s, but are in fact one singular element. Visually there are three, but functionally there are only two elements.

It's worth noting that the reason I'd like to keep it as one <span> is because the content of the <span> is dynamic, there's always the possibility of the width of the window changing, and there's a mouseenter and a mouseleave event attached to the <span>.

I have not found a way to do this yet. The most information I've found regarding this behavior on MDN is limited at best. (Info 1, Info 2). I've found a similar question, but it's not the same. At the very least, I'd be fine with giving up my hopes of a border and border-radius and just settle for some padding to the end of a line and the beginning of a new line.

I have a suspicion that this might not be possible based on what I've found and read so far. If it's not possible using native CSS, my first instinct would be to use Javascript to maintain two discrete boxes and automatically adjust where the line wraps whenever either the text or the width changes, but that sounds like a headache and a half.

Here is a basic JSFiddle if you're interested.

example of the problem I'm facing


Solution

  • I think you're looking for box-decoration-break: clone;. For Chromium and webkit browsers, you need to prefix the property with -webkit-. So

    div {
      border: 1px solid lightgray;
      width: 600px;
      margin: 10px 0;
    }
    
    span {
      background-color: gray;
      border: 3px solid red;
      border-radius: 4px;
      line-height: 1.7em;
      margin: 1px;
      padding: 2px 5px;
      -webkit-box-decoration-break: clone;
      box-decoration-break: clone;
    }
    <div>
      <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit</span>
      <span>, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi</span>
    </div>